Returning complete words from a substringBy Bill Graziano on 9 February 2001 | Tags: SELECT melanie writes "I am trying to return a string using
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:
we'd get something like this:
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:
and our result would look something like this:
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.
And the results from the two queries:
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.
|
- Advertisement - |