0

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,  
3

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.