How to get text between two words/characters

前端 未结 4 833
不知归路
不知归路 2021-01-27 01:15

How can I get some text between two known words?

Sub-select example:

(SELECT TOP(1)Note
FROM Clients
WHERE (ID=@ID) AND (Note IS NOT NULL) AND (Note NOT         


        
4条回答
  •  误落风尘
    2021-01-27 01:40

    Maybe something like this:

    You try to find the last occurence. This is the first in a reverted string...

    --This is a mockup of your table to hold your strings:

    DECLARE @tbl TABLE(YourLine VARCHAR(100));
    INSERT INTO @tbl VALUES
     ('Blablabla bla bla blabla bla bla bla (21.08.2015) "some text" word bla bla')
    ,('Blablabla bla bla blabla bla bla bla (25.08.2015) "another text" word bla bla') 
    ,('Blablabla bla bla blabla bla bla bla (28.08.2015) "TEXT I NEED TO GET" word bla bla blabla bla bla.');
    

    --Here I specify the word you are searching for

    DECLARE @SearchWord VARCHAR(100)='word';
    

    --This is the query

    SELECT REVERSE(C.CutOut) AS YourSnippet
    FROM @tbl AS tbl
    

    --CROSS APPLY works row-wise: Take the current line and revert it!

    CROSS APPLY(SELECT REVERSE(tbl.YourLine) AS RevLine) AS A
    

    --Find the first occurence of ) and the first occurence of the reverted searchword!

    CROSS APPLY(SELECT CHARINDEX(')',A.RevLine) AS PosParanthesis
                      ,CHARINDEX(REVERSE(@SearchWord),A.RevLine) AS PosWord) AS B 
    

    --Cut the string at the position found to the length calculated

    CROSS APPLY(SELECT SUBSTRING(A.RevLine,B.PosWord + LEN(@SearchWord)+1,B.PosParanthesis-B.PosWord-LEN(@SearchWord)-1) AS CutOut) AS C
    

    The result of the las CROSS APPLY is your target string, but reverse. Therefore a last reverse in the main SELECT...

提交回复
热议问题