sql-server-2005 - varchar() 和 nvarchar() 之间奇怪的 SQL Server 2005 排序规则差异

标签 sql-server-2005 tsql unicode collation nvarchar

有人可以解释一下:

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 文本比较不是这种情况。

比较 -XiX ,就像比较XiX , 所以 -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/

相关文章:

sql - 外键引用 SQL Server 中的 2 列主键

SQL 服务器 : combine only dates with no reference

tsql - 触发触发器时,如何在SQL事件探查器中查看变量值?

Java:寻找最快的方法来检查字符串是否存在特定范围内的 Unicode 字符

visual-studio-2008 - 如何让 Visual Studio 2008 在不安装 SQL Business Intelligence Development Studio 2005 的情况下编辑 SSRS 2005 报表项目?

sql-server-2005 - 如何在 SQL Server 2005 中替换部分 XML 节点

sql - 逗号分隔的 SQL 字符串 需要分隔

sql - 如何在T-SQL中右连接日期表?

swift - 如何显示彩色表情符号

google-app-engine - Google App Engine Python 2.7 + lxml = Unicode ParserError