How to check string length and then select substri

2019-04-03 06:38发布

问题:

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

回答1:

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