SQL 数据类型 text 不能用作 UNION、INTERSECT 或 EXCEPT 运算符的操作数,因为它不可比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34897677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:21:06  来源:igfitidea点击:

The data type text cannot be used as an operand to the UNION, INTERSECT or EXCEPT operators because it is not comparable

sqlsql-servertsqlunion

提问by Alexander

I have a table

我有一张桌子

  • Id (PK)
  • Owner int
  • DescriptionText text
  • 标识(PK)
  • 所有者信息
  • 说明文字文字

which is joined to another table

连接到另一个表

  • Id (FK)
  • Participant int
  • 身 (FK)
  • 参与者信息

The Owner can be a Participant, and if it is, the same reference (into user table) is in Owner and Participant. So I did:

所有者可以是参与者,如果是,则所有者和参与者中有相同的引用(进入用户表)。所以我做了:

SELECT TableA.Id,TableA.Owner,TableA.Text
FROM TableA
WHERE TableA.Owner=@User
UNION
SELECT TableA.Id,TableA.Owner.TableA.Text
FROM TableA LEFT JOIN TableB ON (TableA.Id=TableB.Id)
WHERE TableB.Participant = @User

This query should return all distinct data sets where a certain @User is either Owner or Participant or both.

此查询应返回所有不同的数据集,其中某个@User 是所有者或参与者或两者。

And it would, if SQL Server wouldn't throw

它会,如果 SQL Server 不会抛出

The data type text cannot be used as an operand to the UNION, INTERSECT or EXCEPT operators because it is not comparable.

数据类型 text 不能用作 UNION、INTERSECT 或 EXCEPT 运算符的操作数,因为它不可比较。

Since Id is a PK, and Text is from the same table, why would SQL Server want to compare Text at all?

既然 Id 是一个 PK,而 Text 来自同一个表,那么 SQL Server 为什么要比较 Text 呢?

I can use UNION ALLto stop duplicate detection, but can I circumvent this without losing the distinctness of the results?

我可以UNION ALL用来停止重复检测,但是我可以在不丢失结果的清晰性的情况下规避它吗?

回答by Lukasz Szozda

Correct way

正确方式

Stop using TEXTit is obsolete. Alter table schema.

停止使用TEXT它已经过时了。更改表架构。

ntext, text, and imagedata types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

ntext、text 和 image数据类型将在 Microsoft SQL Server 的未来版本中删除。避免在新的开发工作中使用这些数据类型,并计划修改当前使用它们的应用程序。请改用 nvarchar(max)、varchar(max) 和 varbinary(max)。

Workaround

解决方法

Cast to NVARCHAR(MAX):

投射到NVARCHAR(MAX)

SELECT TableA.Id,TableA.Owner, CAST(TableA.DescriptionText AS NVARCHAR(MAX))
FROM TableA
WHERE TableA.Owner=@User
UNION
SELECT TableA.Id,TableA.Owner, CAST(TableA.DescriptionText AS NVARCHAR(MAX))
FROM TableA LEFT JOIN TableB ON (TableA.Id=TableB.Id)
WHERE TableB.Participant = @User