ORDER BY … COLLATE in SQL Server

此生再无相见时 提交于 2019-11-28 03:44:19

问题


Under SQL Server. A table contains some text with different cases. I want to sort them case-sensitive and thought that a COLLATE in the ORDER BY would do it. It doesn't. Why?

CREATE TABLE T1 (C1 VARCHAR(20))
INSERT INTO T1 (C1) VALUES ('aaa1'), ('AAB2'), ('aba3')

SELECT * FROM T1 ORDER BY C1 COLLATE Latin1_General_CS_AS
SELECT * FROM T1 ORDER BY C1 COLLATE Latin1_General_CI_AS

Both queries return the same, even if the first one is "CS" for case-sensitive

aaa1
AAB2
aba3

(in the first case, I want AAB2, aaa1, aba3)

My server is a SQL Server Express 2008 (10.0.5500) and its default server collation is Latin1_General_CI_AS.

The collation of the database is Latin1_General_CI_AS too.

The result remains the same if I use SQL_Latin1_General_CP1_CS_AS in place of Latin1_General_CS_AS.


回答1:


Because that is the correct case sensitive collation sort order. It is explained in Case Sensitive Collation Sort Order why this is the case, it has to do with the Unicode specifications for sorting. aa will sort ahead of AA but AA will sort ahead of ab.




回答2:


You need a binary collation for your desired sort order with A-Z sorted before a-z.

SELECT * FROM T1 ORDER BY C1 COLLATE Latin1_General_bin

The CS collation sorts aAbB ... zZ



来源:https://stackoverflow.com/questions/13822220/order-by-collate-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!