Search code examples
stringt-sqlparsingsplitcharindex

How to get the second word in a string using t-sql?


I would like to extract the second word from a string or the phrase between the first and third spaces.

for example

'The Boeing Corporation'

I would like 'Boeing'


Solution

  • declare @sentence nvarchar(264);
    
    set @sentence = 'The Boeing Corporation';
    
    select ltrim(substring(@sentence,charindex(' ',@sentence), CHARINDEX(' ',ltrim(SUBSTRING(@sentence,charindex(' ',@sentence),LEN(@sentence)-charindex(' ',@sentence)))) ))
    
    | (No column name) |
    | :--------------- |
    | Boeing           |
    

    db<>fiddle here