Note: I believe this is no duplicate of this seemingly related question, since I’ve got actual strings that contain a number instead of integers stored as strings like the other OP.
I’m looking for a way to output SQL strings ordered in natural order by a number they contain, like a numerical infix. For example, Windows Explorer does that naturally:
On DBA, I read that numbers alone have no properties for alphabetical sorting, but I’m sure there’s some way of doing that for infix numbers without leading zeros, because they are significant.
In SQL Server 2008 R2, my scenario is somewhat like this:
DECLARE @Table TABLE (ID INT, Name VARCHAR(10));
INSERT INTO @Table (ID, Name) VALUES
(1,'name1file'), (5,'name11file'),
(2,'name2file'), (6,'name20file'),
(3,'name3file'), (7,'name21file'),
(4,'name10file');
SELECT * FROM @Table ORDER BY Name COLLATE Latin1_General_100_BIN ASC;
Exemplary result sets:
Output got Output desired
ID | Name ID | Name
========== ==========
1 | name1file 1 | name1file
4 | name10file 2 | name2file
5 | name11file 3 | name3file
2 | name2file 4 | name10file
6 | name20file 5 | name11file
7 | name21file 6 | name20file
3 | name3file 7 | name21file
The ID
column is for illustrative purposed only (you could just ORDER BY ID
in that case). It’s just the VARCHAR
column I query. I tried using COLLATE
, but none of the fn_helpcollations
I tried produced the desired order.
So, is there a way to achieve that without using SUBSTRING
or PATINDEX
or CLR functions or other means of extracting the number, maybe by using an appropriate collation?
If not, is there a reason this common use case is not implemented in any of the thousands of collations? I hoped that Windows Explorer used some common collation for that instead of a function implementation like PHP’s natsort()
.