2016-04-20 32 views
1

我有一個表保存一個字符串,如柱的一部分:TSQL - 只提取動態字符串

xx-xx-xxx-84 
xx-25-xxx-xx 
xx-xx-123-xx 

我要繼續前進,查詢出唯一的數字,但你可以看,數字每次都放在字符串中的不同位置。有沒有去查詢字符串中的數字?

謝謝, 我很感謝你的時間!

+1

http://stackoverflow.com/questions/11333078/sql-take-just-the-numeric-values-from-a-varchar – Seano666

回答

0

這需要重複應用字符串函數。一種有助於所有嵌套的方法是使用OUTER APPLY。事情是這樣的:

select t3.col 
from t outer apply 
    (select t.*, patindex(t.col, '[0-9]') - 1 as numpos) t1 outer apply 
    (select t1.*, substring(t1.col, t1.numpos, len(t1.col)) as col2) t2 outer apply 
    (select t2.*, 
      (case when col2 like '%-%' 
        then substring(t2.col, charindex('-', t2.col)) 
        else t2.col 
       end) as col3 
    ) t3 
0

最簡單的方式(知道只有「x」和「 - 」是字符串):

SELECT REPLACE(REPLACE(s,'x',''),'-','') FROM T 

或者,如果X可以再使用PATINDEX() function任何非數字字符:

SELECT S, SUBSTRING(S, 
        PATINDEX('%[0-9]%',s), 
        PATINDEX('%[0-9][^0-9]%',s) 
        +PATINDEX('%[0-9]',s) 
        +1 
        -PATINDEX('%[0-9]%',s)) as digit 
FROM T