有人可以解释一下:
SELECT
CASE WHEN CAST('iX' AS nvarchar(20))
> CAST('-X' AS nvarchar(20)) THEN 1 ELSE 0 END,
CASE WHEN CAST('iX' AS varchar(20))
> CAST('-X' AS varchar(20)) THEN 1 ELSE 0 END
结果: 0 1
SELECT
CASE WHEN CAST('i' AS nvarchar(20))
> CAST('-' AS nvarchar(20)) THEN 1 ELSE 0 END,
CASE WHEN CAST('i' AS varchar(20))
> CAST('-' AS varchar(20)) THEN 1 ELSE 0 END
结果: 1 1
在第一个查询中,
nvarchar()
结果不是我所期望的,但删除了 X
制作 nvarchar()
排序按预期发生。(我的原始查询使用
''
和 N''
文字语法来区分 varchar()
和 nvarchar()
而不是 CAST()
并得到相同的结果。)数据库的排序规则设置为
SQL_Latin1_General_CP1_CI_AS
.
最佳答案
在比较 unicode 文本时,连字符会被特殊对待。 Unicode 比较使用“字典顺序”,它忽略连字符。非 unicode 文本比较不是这种情况。
比较 -X
和 iX
,就像比较X
和 iX
, 所以 -X
,左侧更大。
当比较“-”和“i”时,就像比较“”和“i”,所以“i”,右边更大。
从 MSDN,
A SQL collation's rules for sorting non-Unicode data are incompatible with any sort routine that is provided by the Microsoft Windows operating system; however, the sorting of Unicode data is compatible with a particular version of the Windows sorting rules. Because the comparison rules for non-Unicode and Unicode data are different, when you use a SQL collation you might see different results for comparisons of the same characters, depending on the underlying data type. For example, if you are using the SQL collation "SQL_Latin1_General_CP1_CI_AS", the non-Unicode string 'a-c' is less than the string 'ab' because the hyphen ("-") is sorted as a separate character that comes before "b". However, if you convert these strings to Unicode and you perform the same comparison, the Unicode string N'a-c' is considered to be greater than N'ab' because the Unicode sorting rules use a "word sort" that ignores the hyphen.
SELCT body From MSDN_Articles WHERE url IN
("http://support.microsoft.com/kb/322112")
关于sql-server-2005 - varchar() 和 nvarchar() 之间奇怪的 SQL Server 2005 排序规则差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3056967/