SQL select to get a string between two spaces

后端 未结 3 885
借酒劲吻你
借酒劲吻你 2021-01-06 23:02

I have a field with names in the format DOE JOHN HOWARD or DOE JOHN H.

I need a query to get the string between the two spaces (JOHN in this case).

The SO an

3条回答
  •  盖世英雄少女心
    2021-01-06 23:38

    After doing some searches to resolve my problem, realised there is no generic answer, so below is piece of code to find string between some other strings. I think it may be useful for somebody in future.

    DECLARE @STRING NVARCHAR(MAX) = 'Something here then stringBefore Searching stringAfter something there.'
    DECLARE @FIRST NVARCHAR(20) = 'stringBefore'
    DECLARE @SECOND NVARCHAR(20) = 'stringAfter'
    DECLARE @SEARCHING NVARCHAR (20)
    
    SET @SEARCHING = (SELECT SUBSTRING(@STRING, CHARINDEX(@FIRST, @STRING) + LEN(@FIRST), CHARINDEX(@SECOND, @STRING) - CHARINDEX(@FIRST, @STRING) - LEN(@FIRST))) 
    -- if you want to remove empty spaces
    SET @SEARCHING = REPLACE(@SEARCHING, ' ', '')
    SELECT @SEARCHING
    

    Then output as below:

    (No column name)

    Searching

提交回复
热议问题