SQL截取一個欄位中不確定字母和數字並按照數字順序排序

來源:互聯網
上載者:User

 


-------------------------
--建立時間:08-3-11
--建立人:WJH
--功能:拆分testContent欄位並按照數字排序
-------------------------

--建立暫存資料表
CREATE TABLE #a (testID INT identity(1,1),testContent VARCHAR(50))

--插資料
INSERT #a SELECT 'A10'
INSERT #a SELECT 'A1'
INSERT #a SELECT 'A12'
INSERT #a SELECT 'A2'
INSERT #a SELECT 'A25'

--查詢
SELECT * FROM #a order by Cast((substring(testContent,Cast((patindex('%[0-9]%',testContent)) as int),100)) as int)

--刪除表
DROP TABLE #a

testID      textContext                                       
----------- --------------------------------------------------
2           A1
4           A2
1           A10
3           A12
5           A25

以上是利用patindex數字出現的位置,然後截取此位置到最後的(100位很長了)數字,並按照其排序

更複雜些的按照左右兩部分截取的排序

-------------------------
--建立時間:08-3-11
--建立人:WJH
--功能:拆分testContent欄位並按照數字排序
-------------------------

--建立暫存資料表
CREATE TABLE #a (testID INT identity(1,1),testContent VARCHAR(50))

--插資料
INSERT #a SELECT 'A10'
INSERT #a SELECT 'A1'
INSERT #a SELECT 'A12'
INSERT #a SELECT 'A2'
INSERT #a SELECT 'A25'
INSERT #a SELECT 'B10'
INSERT #a SELECT 'B1'
INSERT #a SELECT 'B12'
INSERT #a SELECT 'B2'
INSERT #a SELECT 'B25'

--查詢
select * from #a   
order by left(testContent,patindex('%[0-9]%',testContent)-1),
Cast((substring(testContent,Cast((patindex('%[0-9]%',testContent)) as int),100)) as int)

--刪除表
DROP TABLE #a

 

testID      testContent                                       
----------- --------------------------------------------------
2           A1
4           A2
1           A10
3           A12
5           A25
7           B1
9           B2
6           B10
8           B12
10          B25

(所影響的行數為 10 行)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.