假设最大字符数between/before/after : is 3
,您可以使所有字符串值的长度和顺序相同,如下所示。不过看起来有点复杂!
小提琴演示
;with cte as (
select val, charindex(':',val,1) index1,
charindex(':',val,charindex(':',val,1)+1) index2
from t
)
select val,right('000' + left(val,index1-1),3) + ':' +
case when index2-index1>0
then right('000' + substring(val,index1+1,index2-index1-1),3)
else right('000' + substring(val,index1+1,len(val)),3) end + ':' +
case when index2>0
then right('000' + right(val, len(val) - index2),3)
else '000' end As odr
from cte
order by odr
| VAL | ODR |
--------------------------
| 01:01 | 001:001:000 |
| 01:02 | 001:002:000 |
| 02:01 | 002:001:000 |
| 03:01:01 | 003:001:001 |
| 03:01:02 | 003:001:002 |
| 04:01 | 004:001:000 |
| 09:01N | 009:01N:000 |
| 10:01 | 010:001:000 |
| 11:01N | 011:01N:000 |
| 104:01 | 104:001:000 |
| 105:01 | 105:001:000 |