you can always convert your varchar-column to bigint as an integer might be too short ...
select cast([yourvarchar] as BIGINT)
but you should always take care of alpha characters
where ISNUMERIC([yourvarchar] +'e0') = 1
the + 'e0' comes from http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber
this will lead to your statement
SELECT * FROM Table ORDER BY ISNUMERIC([yourvarchar] +'e0') DESC , LEN([yourvarchar]) ASC
the first sort column will place the numeric value on top. the second sorts by length, so 10 will be preceded by 0001 (what's stupid ?!)
this leads to the second version:
SELECT * FROM Table ORDER BY ISNUMERIC([yourvarchar] +'e0') DESC , RIGHT('00000000000000000000'+[yourvarchar], 20) ASC
the second column now gets the right to "0", so natural sorting puts integers with leading zeros (0,01,10,0100 ...) in the correct order (right!) - but all alpha will be expanded using '0'- characters (execution)
therefore the third version:
SELECT * FROM Table ORDER BY ISNUMERIC([yourvarchar] +'e0') DESC , CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1 THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC ELSE LTRIM(RTRIM([yourvarchar])) END ASC
now the numbers are first filled with "0'-characters" (of course, the length of 20 can be increased) - which sorts the numbers on the right - and alpha only cuts off
Bernhard Apr 03 '13 at 7:35 am
source share