I have a requirement where I have to apply sort in an SQL query by an Alphanumeric column such that the values in it get sorted like the following:
AD
AH
AK1
B1
B2
B3x
B3y
B11
C1
C6
C12x
UIP
instead of the default way:
AD
AH
AK1
B1
B11
B2
B3x
B3y
C1
C12x
C6
UIP
I was able to write the following SQL statement:
SELECT [MyColumn]
FROM [MyTable]
ORDER BY
LEFT([MyColumn], PATINDEX('%[0-9]%', [MyColumn]) - 1),
CONVERT(INT, SUBSTRING([MyColumn], PATINDEX('%[0-9]%', [MyColumn]), LEN([MyColumn]) - (PATINDEX('%[0-9]%', REVERSE([MyColumn]))))),
RIGHT([MyColumn], PATINDEX('%[0-9]%', [MyColumn]) - 1)
I just need to know how to implement this in a conditional way such that this doesn't get triggered for alpha-only value else it would give error, or if there is a way to make it work with that as well?
P.S. The environment is SQL Server 2014.
'B3y2'
and'B3y11'
? If so, which should be ordered first? Edit: Also, if the answer is yes, how many levels could you therefore get to? Could you end up with a record with the value'B3y11A3d12AS4'
?