使用SQL Server/C进行字母数字排序#

我有字母数字数字。应用排序直通SQL服务器ORDER BY条款后,我得到以下结果使用SQL Server/C进行字母数字排序#

select * 

from WO

where WOCode = AnyNumber

order by [ColumnName]

结果:

39660A1 

39660A10

39660A11

39660A2

39660A3

39660A4

39660A5

39660A6

39660A7

39660A8

39660A9

所需的结果

39660A1 

39660A2

39660A3

39660A4

39660A5

39660A6

39660A7

39660A8

39660A9

39660A10

39660A11

回答:

这里是一个快速和肮脏的解决方案:

SELECT * 

FROM table

ORDER BY LEN(Field) ASC, Field ASC

演示here。

回答:

假设字母A始终处于相同的位置,并且后面的字符是整数只有

然后,你可以这样做:

WITH CTE AS 

(

SELECT

WOCode,

CAST(SUBSTRING(WOCode, CHARINDEX('A', WOCode) + 1,

LEN(WOCode) - CHARINDEX('A', WOCode) + 1) AS INT) AS DisplayOrder

FROM

WO

)

SELECT *

FROM CTE

ORDER BY DisplayOrder;

Demo

结果:

| WOCode | 

|----------|

| 39660A1 |

| 39660A2 |

| 39660A3 |

| 39660A4 |

| 39660A5 |

| 39660A6 |

| 39660A7 |

| 39660A8 |

| 39660A9 |

| 39660A10 |

| 39660A11 |

您还可以使用TRY_CAST,以避免可能的结果,因为使用铸铁与非整数值的错误(感谢@ zambonee的建议):

WITH CTE AS 

(

SELECT

WOCode,

CASE

WHEN TRY_CAST(WOCode AS INT) IS NULL

THEN CAST(SUBSTRING(WOCode,

CHARINDEX('A', WOCode) + 1,

LEN(WOCode) - CHARINDEX('A', WOCode) + 1) AS INT)

ELSE 0

END AS DisplayOrder

FROM

WO

)

SELECT *

FROM CTE

ORDER BY DisplayOrder;

updated demo

以上是 使用SQL Server/C进行字母数字排序# 的全部内容, 来源链接: utcz.com/qa/267193.html

回到顶部