如何从sql中的列中获取某个字符串

时间:2015-11-03 11:26:55

标签: sql sql-server tsql

列名主题

Value = Something TEST001 something

我需要从“Something TEST001 Something”获得TEST001

如果在TEST001的1之后有空格或任何特殊字符,它们将被删除。

我只有这个

SELECT   
    Subject
    , REPLACE(SUBSTRING(MailSubject, CHARINDEX('TEST', MailSubject), LEN(MailSubject)),'', '') AS Assingment
FROM    
    AssingmentEmail 

来自TEST001的数字可以更多,但如果有任何空格或非数字,它将被删除。

3 个答案:

答案 0 :(得分:1)

基于评论,这里是编辑的解决方案:

DECLARE @t TABLE(v VARCHAR(100))
INSERT INTO @t VALUES
('Something TEST001 something'),
('Something [TEST0001] something'),
('Something TEST001 something 123 something'),
('Something {TEST0001} something 123 something')

;WITH cte AS(SELECT SUBSTRING(v, CHARINDEX('TEST', v), LEN(v)) AS v FROM @t)
SELECT SUBSTRING(v, 1, PATINDEX('%[^TEST0-9]%', v) - 1) AS v FROM cte

输出:

v
TEST001
TEST0001
TEST001
TEST0001

说明:

cte中,您正在选择子字符串:

TEST001 something
TEST0001] something
TEST001 something 123 something
TEST0001} something 123 something

然后,您正在搜索第一次出现的带有T E S T 0 1 2 3...9 %[^TEST0-9]%的符号,并获得子串直到该符号。

答案 1 :(得分:0)

我会使用子查询来完成此操作。处理中间结果更容易。首先,在" TEST"之前摆脱该部分。然后,将结果放在第一个第一个空格中:

select left(ms1, charindex(' ', ms1)) as TestStuff
from (select stuff(MailSubject, 1, charindex(' TEST', MailSubject), '') as ms1
      from assignment email
     ) ae

答案 2 :(得分:0)

结合使用SUBSTRINGCHARINDEX& LEN。无论TESTXXXX中有多少位数,它都可以工作。

SELECT MailSubject,
LEFT(SUBSTRING([MailSubject], CHARINDEX('TEST', [MailSubject]), LEN([MailSubject])), CHARINDEX(' ', SUBSTRING([MailSubject], 
CHARINDEX('TEST', [MailSubject]), LEN([MailSubject]))) - 1) AS [MailSubject]
FROM AssingmentEmail

INPUT:

MailSubject
something TEST001 something 
something TEST201 something
something TEST20122 something
something TEST601 something

输出:

MailSubject                      MailSubject
something TEST001 something      TEST001
something TEST201 something      TEST201
something TEST20122 something    TEST20122
something TEST601 something      TEST601

SQL FIDDLE:http://sqlfiddle.com/#!3/93660d/1/0