清理不需要的字符后,tsql转换为bigint

时间:2018-01-14 04:17:13

标签: sql-server tsql sql-server-2012 ssms

我想将以下数据行清理为bigint:

"0000000008/314282" 
"00000000  6058829" 
"00000000 80239283" 
"0000000  80272516" 
"000000000 5428588" 
"00000000 80328516" 
"00000000 81597613" 
"000000008159*2693" 
"00000000 81585289" 
"00000000 81601382" 
"00000000 81727962" 
"00000000101*79919" 
"0000000  81607533" 
"0000000  81605092" 
"0000000  81606197" 
"000000000 7376759" 
"0000000  81667128"

clean up the unwanted characters

你会注意到有些斜线" /"介于两者之间有些星号" *"而有些则介于两者之间。

我想在查询中编写一个函数或技术,将带有这些不需要的字符(/ *空格)的所有行清理成bigint。

1 个答案:

答案 0 :(得分:1)

如果你需要的是替换你的字符串的所有非数字字符并使其成为数字值,请尝试以下

DECLARE @Num VARCHAR(20) = '977C2CSDC132/*'
;WITH CTE
AS
(
    SELECT
        SeqNo = LEN(@Num),
        MyNum = CAST(@Num AS VARCHAR(20)),
        NumLen = LEN(@Num),
        PrevChar = 1

    UNION ALL
    SELECT
        SeqNo = SeqNo-1,
        MyNum = CAST(
                CASE WHEN ISNUMERIC(SUBSTRING(MyNum,PrevChar,1))=1
                    THEN MyNum
                ELSE REPLACE(MyNum,SUBSTRING(MyNum,PrevChar,1),'') END
                AS VARCHAR(20)),
        NumLen = NumLen,
        PrevChar = CASE WHEN ISNUMERIC(SUBSTRING(MyNum,PrevChar,1))=1
                        THEN PrevChar+1
                    ELSE PrevChar END
        FROM CTE
            WHERE SeqNo >0
)   
SELECT
    MyNum = CAST(MyNum AS BIGINT)
    FROM CTE
        WHERE SeqNo = 0