Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check string length and then select substring in Sql Server

In a view, i have a column comments which may contain large string. I just want to select first 60 characters and append the '...' at the end of the selected string.

For selecting first 60 characters i have used following query:

select LEFT(comments, 60) as comments from myview 

Now i want its processing as below:

  1. Check it contains more then 60 characters or not.
  2. If contains then select only first 6o characters and append three dots at the end.
  3. If it doesn't contain more then 60 characters then select whole string without appending three dots at the end.

Thanks

like image 867
Code Rider Avatar asked Feb 26 '13 14:02

Code Rider


1 Answers

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60               THEN comments              ELSE LEFT(comments, 60) + '...'         END  As Comments FROM    myView 
  • SQLFiddle Demo
like image 58
John Woo Avatar answered Sep 28 '22 18:09

John Woo