I have a varchar column conteining a code, this code could by only numbers, or number prefixed by a char for example i have a column containing this data :
CASE
WHEN ISNUMERIC(Col) = 1 THEN '@'
Else LEFT(Col, 1)
END
,CASE
WHEN ISNUMERIC(Col) = 1 THEN Convert(int, Col)
Else Convert(int, RIGHT(Col, LEN(Col) - 1))
END
SELECT Code FROM Code_List ORDER BY Code, CASE WHEN ISNUMERIC(SUBSTRING(Code,1,1)) = 1 THEN CODE ELSE SUBSTRING(Code,2,LEN(Code)-1) END
Obviously assuming that only the first digit can be alpha
you might try
...ORDER by ('A'+Code)
Assuming there's no spaces before the values and there can only be 1-char prefix:
ORDER BY
CASE WHEN LEFT(Code, 1) BETWEEN '0' AND '9' THEN ' ' ELSE LEFT(Code, 1) END,
CAST(STUFF(Code, 1, CASE WHEN LEFT(Code, 1) BETWEEN '0' AND '9' THEN 0 ELSE 1 END, '') AS int)
Alternatively, the second criterion could be rewritten like this:
CAST(STUFF(Code, 1, PATINDEX('[^0-9]%', Code), '') AS int)
PATINDEX('[^0-9]%', Code)
returns 1 if it finds a non-numeric character at the beginning of Code
, and 0 otherwise. As a result, STUFF
either removes 1 character, or none, i.e. same as previously.