Home Forums SQL Server 2005 T-SQL (SS2K5) Extracting a specific number of words from a string in sql RE: Extracting a specific number of words from a string in sql

  • This may look a little funky, but it does the job 🙂

    declare @x table ( words varchar(50) not null )

    insert @x

    select 'This is the first line' union all

    select 'Second line' union all

    select 'Word' union all

    select 'This is the fourth line'

    selectcase when charindex(' ', words, charindex(' ', words) + 1) = 0

    then words

    else left(words, charindex(' ', words, charindex(' ', words) + 1))

    end

    from @x

    go

    --------------------------------------------------

    This is

    Second line

    Word

    This is

    (4 row(s) affected)

    /Kenneth