Achieving consistent sorting between c# and SQL using CollationInfo.Comparer

耗尽温柔 提交于 2020-01-11 10:03:07

问题


I am attempting to use CollationInfo.Comparer from SMO to get my c# code to sort like SQL Server. I have gotten the correct collation, but my items still do not sort correctly.

var collationInfo = CollationInfo.Collations.Single(x => x.Name == "SQL_Latin1_General_CP1_CS_AS") as CollationInfo;
var comparer = collationInfo.Comparer;

int c = comparer.Compare("Tri-Valley L", "Trimble L");

In this case c returns '1' indicating that Tri-Valley L will come after Trimble.

However this code in SQL Server

DECLARE @T TABLE
(
    Name VARCHAR(20)
)

INSERT INTO @T
(
    Name
)
VALUES('Tri-Valley L'),
    ('Trimble L')

SELECT
Name
FROM
@T
ORDER BY Name

Returns Tri-Valley before Trimble.

Does the collation compare stuff just not work correctly, or am I doing something wrong?


回答1:


The legacy "SQL" collation sorting is not aligned with Windows "word-sort" algorithm. You'll need to use a Windows collation (e.g. Latin1_General_CS_AS) for the columns in the database to get the same behavior.



来源:https://stackoverflow.com/questions/11562042/achieving-consistent-sorting-between-c-sharp-and-sql-using-collationinfo-compare

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