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

  • Adam Haines - Wednesday, February 27, 2008 7:32 AM

    I found a function that may be more along the lines of what you are looking for. This function requires two inputs and the number of words you would like returned. I did not write the code and will give credit to the programmer. His link is http://www.tom-muck.com/blog/index.cfm?newsid=72CREATE FUNCTION udf_GetNumberOfWords ( @stringToSplit varchar(8000), @numberOfWords int)RETURNS varchar(8000) AS BEGIN DECLARE @currentword varchar(8000)DECLARE @returnstring varchar(8000)DECLARE @wordcount intSET @wordcount = 0SET @returnstring = ''SET @currentword = ''SET @stringToSplit = ltrim(rtrim(@stringToSplit))Declare @index intWHILE @wordcount 0 BEGIN Select @index = CHARINDEX(' ', @stringToSplit) if @index = 0 BEGIN SELECT @currentword = ltrim(rtrim(@stringToSplit)) SELECT @wordcount = @numberOfWords END else BEGIN IF (len(@stringToSplit) - @index > 0) BEGIN SELECT @currentword = ltrim(rtrim(LEFT(@stringToSplit, @index-1)))--the new shortened string SELECT @stringToSplit = RIGHT(@stringToSplit,LEN(@stringToSplit) - @index) -- the rest END END SELECT @returnstring = @returnstring + ' ' + @currentword SELECT @wordcount = @wordcount + 1 ENDSET @returnstring = LTRIM(@returnstring)RETURN @returnstringENDThe function can be called like this: (2 is the number of words to return)select dbo.udf_GetNumberOfWords(mycolumn,2)from mytable

    Thanks so much, Cool script 😀