SQLTeam.com Logo

Return to Returning complete words from a substring

Returning complete words from a substring

Written by Bill Graziano on 09 February 2001

melanie writes "I am trying to return a string using Select *, left (newsitembodytext, 150) . . . As you can guess it is returning incomplete words. I need the last word to be complete any ideas?" I think we can put some string functions to use and solve this one.

Just for completeness, the entire text of Melanie's query is:

Select *, left (newsitembodytext, 150) as shortbody 
from tbl_industry_news 
where active = 1 
and Communications = 1 
order by listingNumber

On to those sting functions! You started out using the LEFT function which a very good string function. Your example will return the first 150 characters starting at the left of the string. The RIGHT function is very similar but will return a given number of characters starting at the right (or end) of a string.

We're going to start with a function called CHARINDEX. The syntax of CHARINDEX is:

CHARINDEX(expression1, expression2 [, start_location])

CHARINDEX returns the start position of expression1 in expression2. If we ran this little snippet of code:

SELECT START = CHARINDEX('yak', 'I am the Yak')

we'd get something like this:

START       
----------- 
10

(1 row(s) affected)

We can also use the start_location parameter to start our search at a given position. Let's say we were searching for the first space character after the sixth character in our sample string. Our query might look like this:

SELECT START = CHARINDEX(' ', 'I am the Yak', 6)

and our result would look something like this:

START       
----------- 
9

(1 row(s) affected)

We can now find the first space that falls after any number of characters that we want. Let's see if we can start rewriting that SELECT statement. First, we'll have the original and then the enhanced version. Note that I shortened it to 20 characters for easier reading.

Select 	LEFT (newsitembodytext, 20 ) as shortbody 
from 	tbl_industry_news 

Select 	LEFT (newsitembodytext, CHARINDEX(' ', newsitembodytext, 20) ) as shortbody 
from 	tbl_industry_news

And the results from the two queries:

shortbody            
-------------------- 
Wild Yak trading rea
Agriculture is key t

(2 row(s) affected)

shortbody                                
---------------------------------------- 
Wild Yak trading reached 
Agriculture is key to 

(2 row(s) affected)

You'll note that the first result set has the string truncated in the middle while the second has a nice break in between words. You should be able to use this to get the results you want. Enjoy.