Limit the text returned from a field using SQL

In most databases today there are columns that contain thousands of characters of text. In some cases this information needs to be returned to an end user on a busy section of your site, for example a search feature.

If someone does a search on your site usually you will be displaying only a portion of that content when displaying the search results. You could very easily return the full content of all your columns to the end user and use your code to stip off the excess data but a much faster way is to strip off what you don't need in SQL before you pass back to your code. One way of doing this is to use the SubString method in SQL Server:

SUBSTRING(ColumnName, start position, end position)

Example below returns the value within PostDetails from the start position up to 150 characters long and calls this new 'field' PostSummary

SUBSTRING(PostDetails,1,150) as PostSummary

Full example:

Select PosterName, PostDate, SUBSTRING(PostDetails,1,150) as PostSummary
From Posts
Where <<search conditions entered from search page>>

You can easily call PostSummary just like you call PosterName or PostDate in your code view.

SQL
blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

Latest Tweets