Jain Nishant
Jain Nishant

Reputation: 1

Alphanumeric and Numeric sorting in SQL Server

I need to apply sorting on Alphanumeric and Numeric sorting.

Example:

319,
519, 
620, 
1154, 
1195, 
319lov,
319, 
620lov

I need result like:

319,
319,
319lov,
519, 
620, 
620lov,
1154, 
1195, 

I have applied following code to sort:

SELECT Name 
FROM TableName
ORDER BY CAST(CASE
                 WHEN Name LIKE '[0-9][0-9][0-9][0-9]%' THEN LEFT(Name ,4)
                 WHEN Name LIKE '[0-9][0-9][0-9]%' THEN LEFT(Name ,3)
                 ELSE NULL 
              END AS INT)

Got result like:

319,
319lov,
319,
519, 
620,
620lov, 
1154, 
1195,  

Upvotes: 0

Views: 4214

Answers (1)

Mihai
Mihai

Reputation: 26804

SELECT name FROM t 
ORDER BY CONVERT(INT, LEFT(name, PATINDEX('%[^0-9]%', name+'z')-1)),name;

You order by all the numbers up to the first non number,the letter is in there to treat all strings the same.

FIDDLE

Upvotes: 1

Related Questions