I have been asked to sort a locations table in ascending order. The data in the table currently looks something like this:
- 100F01
- 105B02
- 10B01
- GK1-A01
- 201E12
- 20A01
However, when this data is displayed on the screen I want it to sort the numeric results in ascending order and then the string results in alphabetic order. The output should look something like this:
- 10B01
- 20A01
- 100F01
- 105B02
- 201E12
- GK1-A01
I have tried using the following code
SELECT location FROM freelocations
ORDER BY CAST(SUBSTRING(location, 1, 2) AS INT)
however, as expected, this returns an error message because some locations don’t start with a numeric:
Conversion failed when converting the varchar value ‘GK’ to data type int.
Any ideas or tips will be greatly appreciated
Maybe something like this?
(It’s a bit clumsy due to SQL Server lacking a regex replace function)