SQL 按复杂字符串列作为数字排序

SQL order by complex string column as number

我有一个 table 这样的:

| ID | Name | Code  |
---------------------
| 1  | test | 11-2  |
| 2  | test | 11/1  |
| 3  | test | 1     |
| 4  | test | 10x   |
| 5  | test | 11-11 |
| 6  | test | *     |
| 7  | test | 2     |
| 8  | test | m10   |
| 9  | test | 11-*  |
| 10 | test | 11    |
| 11 | test | 10    |

代码列类型为 NVARCHAR。我想获取按代码排序的记录,以便它们像这样排序:

*
1
2
10
10x
11
11-*
11/1
11-2
11-11
m10

但是简单'order by Code'查询returns这个:

*
1
10
10x
11
11-*
11/1
11-11
11-2
2
m10

试试这个

select *,ISNUMERIC(LEFT(t,1)) as num,REPLICATE('0',10-len(t))+RTRIM(t) as ord
from(
select '11-2 ' as t union all
select '11/1 ' union all
select '1    ' union all
select '10x  ' union all
select '11-11' union all
select '*    ' union all
select '2    ' union all
select 'm10  ' union all
select '11-* ' union all
select '11   ' union all
select '10   ' 
)as p

order by num desc,ord