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 :
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.