SQL 将 NTEXT 列与常量值进行比较的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3543570/
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
What's the right way to compare an NTEXT column with a constant value?
提问by noober
If I use something like
如果我使用类似的东西
[ntext2] <> '1,032.5',
I get this error:
我收到此错误:
The data types ntext and varchar are incompatible in the not equal to operator.
数据类型 ntext 和 varchar 在不等于运算符中不兼容。
The best possible solution would be if comparison is implemented in the same way for any column type. (<> operator is applicable for both NVARCHAR and INT).
最好的解决方案是对任何列类型以相同的方式实现比较。(<> 运算符适用于 NVARCHAR 和 INT)。
回答by Guffa
The ntext
data type is deprecated in favour of the nvarchar(max)
data type. If you can change the data type in the table, that would be the best solution. Then there is no problem comparing it to a varchar
literal.
该ntext
数据类型是赞成不赞成使用的nvarchar(max)
数据类型。如果您可以更改表中的数据类型,那将是最好的解决方案。那么将它与varchar
文字进行比较就没有问题了。
Otherwise you would have to cast the value before comparing it:
否则,您必须在比较之前转换该值:
cast([ntext2] as nvarchar(max)) <> '1,032.5'
You might also consider using a nvarchar literal, which solves some similar data type problems:
您也可以考虑使用 nvarchar 文字,它解决了一些类似的数据类型问题:
cast([ntext2] as nvarchar(max)) <> N'1,032.5'
回答by kbrimington
If you would prefer not to cast, you can get by in some scenarios using LIKE
or PATINDEX
, as demonstrated on this MSDN thread: http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/6bd4c661-ea0b-435f-af78-097e61549d41
如果您不想投射,您可以在某些情况下使用LIKE
或PATINDEX
,如此 MSDN 线程所示:http: //social.msdn.microsoft.com/Forums/en-US/transactsql/thread/6bd4c661-ea0b -435f-af78-097e61549d41
The LIKE expression, without wildcards, would be (in this case) roughly equivalent to a test for equality.
没有通配符的 LIKE 表达式(在这种情况下)大致相当于相等性测试。
In this case, the expression would be:
在这种情况下,表达式将是:
[ntext2] NOT LIKE '1,032.5'