Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I sort strings numerically

Status
Not open for further replies.

jhowe

Programmer
May 19, 2000
28
US
I have a varchar field that I want to sort numerically. Typical values are:

1A
1B
5
5A
9
10
10A
12B

and I essentially want to parse the integer at the beginning and sort on that integer. Is this possible in an ORDER BY query? Currently sorting this field gives the alphanumeric order

1A
1B
10
10A
10B
5
5A
9

Thanks in advance.

jhowe
 
This will only work if the last character is the only one that might be a letter.

SELECT
F1,
'JustNum' =
CASE
WHEN ISNUMERIC(F1) = 1 THEN CONVERT(INT, F1)
ELSE CONVERT(INT, SUBSTRING(F1, 1, LEN(F1)-1))
END
from
tablename
ORDER BY
'JustNum', F1

JB
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top