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

  • martin.griffiths (2/27/2008)


    I'm currently trying to write a query that will extract the first two words from a string. I'm using charindex and substrings and it's getting quite messy! Has anyone ever written a function may be to extract a specific number of words i.e. text around spaces please? It would need to be able to cope with data where there are different lengths and number of words such as:

    This is the first line

    Second line

    Word

    This is the fourth line

    and if I was asking it to return a string containing the first two words the results would be:

    This is

    Second line

    Word

    This is

    Thanks.

    Just curious... what will this be used for? In other words, why do you need to do this?

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)