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

1

3

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?

Petasus answered 19/7, 2012 at 13:33 Comment(2)
Just as a sanity check, if you change your SQL sort to ORDER BY Name COLLATE SQL_Latin1_General_CP1_CS_AS, does it still sort in the same order?Crabby
It gives the same result.Petasus
J
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.

Jung answered 20/7, 2014 at 19:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.