SQL Server How to capture a string starting with a specific string and stop after any space

lmyy7pcs  于 2023-05-05  发布在  其他
关注(0)|答案(2)|浏览(115)

I am trying to capture a specific word within a column. I want to extract the word that starts with 'lat'. Basically would like to capture latship , latprod, latdfu
| JobName |
| ------------ |
| pl_blob_consolidated - latship |
| pl_blob - latprod |
| pl_blob - latdfu - final |
| pl_blob - latdfu (final_blob) |
| pl_blob - latdfu - final_blob - sql |

DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, JobName VARCHAR(MAX));

INSERT INTO @tbl (JobName) VALUES
('pl_blob_consolidated - latship'),
('pl_blob - latprod'),
('pl_blob - latdfu - final'),
('pl_blob - latdfu (final_blob)'),
('pl_blob - latdfu - final_blob - sql');

Sample output:

JobName
latship
latprod
latdfu
latdfu
latdfu
select DISTINCT   SUBSTRING(JobName, CHARINDEX('lat', JobName)
     , LEN(JobName) - CHARINDEX('lat', JobName) + 1) 
     , LEN(JobName) - CHARINDEX('lat', JobName) + 1 
 from tableName

Tried this, but won't stop after the word ends.

Thanks

3ks5zfa0

3ks5zfa01#

you can try this with some regular expressions (SQL Server function PATINDEX) : column name myField, table myTable:

SELECT 
/* index of first occurence of lat */
  SUBSTRING(myField, PATINDEX('%lat%', myField), 
/* up to index of first not char or digit or _  */
    PATINDEX('%[^a-zA-Z0-9_]%',         
/* into the string after lat.  (+3 to be after t, up to the end) */
     SUBSTRING(myField, PATINDEX('%lat%', myField) + 3, LEN(myField))) - 1) 
 AS extracted_word
FROM myTable
WHERE myField LIKE '%lat%'
n3h0vuf2

n3h0vuf22#

Please try the following solution.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, JobName VARCHAR(MAX));
INSERT INTO @tbl (JobName) VALUES
('pl_blob_consolidated - latship'),
('pl_blob - latprod'),
('pl_blob - latdfu - final'),
('pl_blob -> latdfu - final_blob'),
('pl_blob - latdfu - final_blob - sql');
-- DDL and sample data population, end

SELECT t.*
    , result = TRIM(value) 
FROM @tbl AS t
    CROSS APPLY STRING_SPLIT(REPLACE(JobName,'->','-'), '-')
WHERE TRIM(value) LIKE 'lat%';

Output

idJobNameresult
1pl_blob_consolidated - latshiplatship
2pl_blob - latprodlatprod
3pl_blob - latdfu - finallatdfu
4pl_blob -> latdfu - final_bloblatdfu
5pl_blob - latdfu - final_blob - sqllatdfu

相关问题