Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

sql - Sorting nvarchar column containing alphanumeric values

One of my columns in a SQL Server 2005 table contains alphanumeric values and I want to sort the rows as per the alphanumeric sorting. HOUSE_NO is a NVARCHAR column and it contains values like this:

 - 2/1 NAWOG
 - 1/1
 - 2/1 A
 - 1/2 A GOLCHA
 - 1
 - 2
 - SHASWAT KUTIR
 - 3 A
 - 11/1
 - 11

And I want them to be sorted as:

 - 1
 - 1/1
 - 1/2 A GOLCHA
 - 2
 - 2/1 A
 - 2/1  NAWAG
 - 3 A
 - 11
 - 11/1
 - SHASWAT KUTIR

I have tried many methods but not successful. I need your suggestions

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yuck. This is not something you're going to want to do in T-SQL against large data sets.

DECLARE @x TABLE(HOUSE_NO NVARCHAR(32));

INSERT @x SELECT '2/1 NAWOG'
UNION ALL SELECT '1/1'
UNION ALL SELECT '2/1 A'
UNION ALL SELECT '1/2 A GOLCHA'
UNION ALL SELECT '1'
UNION ALL SELECT '2'
UNION ALL SELECT 'SHASWAT KUTIR'
UNION ALL SELECT '3 A'
UNION ALL SELECT '11/1'
UNION ALL SELECT '11';

DECLARE @n NVARCHAR(10) = N'%[^0-9]%'

SELECT HOUSE_NO FROM @x
    ORDER BY CASE 
        WHEN HOUSE_NO LIKE N'[0-9]' + @n
        THEN CONVERT(INT, SUBSTRING(HOUSE_NO, 1, PATINDEX(@n, HOUSE_NO)-1))
        WHEN HOUSE_NO NOT LIKE @n THEN CONVERT(INT, HOUSE_NO)
        ELSE 2147483647 END,
        CASE WHEN HOUSE_NO NOT LIKE @n THEN NULL
        ELSE SUBSTRING(HOUSE_NO, PATINDEX(@n, HOUSE_NO), LEN(HOUSE_NO)) END;

What is the point of sorting house numbers in the way anyway?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...