8

Is there a way to easily sort in SQL Server 2005 while ignoring hyphens in a string field? Currently I have to do a REPLACE(fieldname,'-','') or a function to remove the hyphen in the sort clause. I was hoping there was a flag I could set at the top of the stored procedure or something.

Access and the GridView default sorting seems to ignore the hypen in strings.

4

1 に答える 1

19

私もあなたと同じように、何か新しいことを学びました

違いは「文字列ソート」と「単語ソート」(ハイフンを無視)の違いだと思います

WORD ソートと STRING ソートの違いの例 http://andrusdevelopment.blogspot.com/2007/10/string-sort-vs-word-sort-in-net.html

マイクロソフトから http://support.microsoft.com/kb/322112

たとえば、SQL 照合順序「SQL_Latin1_General_CP1_CI_AS」を使用している場合、非 Unicode 文字列「ac」は文字列「ab」より小さくなります。これは、ハイフン (「-」) が「b」の前にある別の文字としてソートされるためです。 . ただし、これらの文字列を Unicode に変換して同じ比較を実行すると、Unicode 文字列 N'a-c' は N'ab' よりも大きいと見なされます。これは、Unicode の並べ替え規則がハイフンを無視する「単語の並べ替え」を使用するためです。 .

COLLATE で遊んで、並べ替えで動作するものを見つけることもできるサンプルコードをいくつか作成しました

DECLARE @test TABLE
(string VARCHAR(50))

INSERT INTO @test SELECT 'co-op'
INSERT INTO @test SELECT 'co op'
INSERT INTO @test SELECT 'co_op'

SELECT * FROM @test ORDER BY string --COLLATE SQL_Latin1_General_Cp1_CI_AS
--co op
--co-op
--co_op

SELECT * FROM @test ORDER BY CAST(string AS NVARCHAR(50)) --COLLATE SQL_Latin1_General_Cp1_CI_AS
--co op
--co_op
--co-op
于 2008-12-11T21:37:21.393 に答える