简体   繁体   中英

SQL: Extract a word from a string

I have a following SQL statement that looks for a certain word after the keyword "dispatch level:".

SELECT SUBSTRING(CadRemarks, CHARINDEX('dispatch level:', CadRemarks) + LEN('dispatch level:'), 6) as 
data
from myTable

I would like to upgrade this statement in a way that will return whatever comes between the keyword "dispatch level:" and anything that comes after the word that I'm looking for. So it could be another word, character, or space. For example:

Dispatch level: XXXXX YYY
or
Dispatch level: XXXXX

Only return XXXXX

EDIT

I'm trying out this SQL, but it selects the word after the word I need, as well.

select left(tt.CadRemarks, charindex(' ', tt.CadRemarks+ ' ')) as data
from myTablet cross apply 
 ( values (substring(CadRemarks, charindex('dispatch level:', CadRemarks) + 
16, len(CadRemarks))) 
 ) tt(CadRemarks)
where t.CadRemarks like '%dispatch level:%'

the where clause is for me to limit the records, but I will have to move it and make the whole thing as CASE statement. But that's later....

Also tried this, but getting an error (invalid length parameter passed to the left...)

SELECT SUBSTRING(CadRemarks, CHARINDEX('dispatch level: ', CadRemarks) + 
LEN('dispatch level: ') + 1, 
CHARINDEX('', CadRemarks) - (CHARINDEX('dispatch level: ', CadRemarks) + 2 + 
LEN('dispatch level: ')))
FROM myTable

Use left() to further find the string:

select left(tt.CadRemarks, charindex(' ', tt.CadRemarks+ ' ')) as data
from table t cross apply 
     ( values (substring(CadtRemarks, charindex('dispatch level:', CadRemarks) + 16, len(CadRemarks))) 
     ) tt(CadRemarks);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM