SQL Server 2012:从字符串中获取SO#

时间:2016-02-12 04:51:58

标签: sql-server

我试图从SQL服务器中的字符串中获取SO#而不使用UDF。例子:

this is the SO#12345 55
this is the SO12345 55
this is the SO 12345 55
this is the SO#12345/55

我想只获取12345,无论特殊字符和空格如何。

1 个答案:

答案 0 :(得分:1)

DECLARE @Table1 TABLE 
    (VAL varchar(23))
;

INSERT INTO @Table1
    (VAL)
VALUES
    ('this is the SO#12345 55'),
    ('this is the SO12345 55'),
    ('this is the SO 12345 55'),
    ('this is the SO#12345/55')
;


SELECT LEFT(subsrt, PATINDEX('%[^0-9]%', subsrt + 't') - 1) 
FROM (
    SELECT subsrt = SUBSTRING(val, pos, LEN(val))
    FROM (
        SELECT val, pos = PATINDEX('%[0-9]%', val)
        FROM @Table1
    ) d
) t