Truncate string in SQL

My question is similar ID: 23018764.  
I would like to truncate a string (title) in MSSQL to 100 char (only if more than 100) at the end of the word nearest to 100 char max (loop for space or whatever) and add ellipsis (...) at the end ONLY if the original string was more than 100 char.

Is this possible in MSSQL?  Is this the best approach or should I write the code in the C# code behind file ASP.NET?

Thanks in advance.  
ALTER PROCEDURE dbo.ftw_Articles_GetArticles
   @PageIndex  int,
   @PageSize   int
   SELECT ftw_Articles.ArticleID, ftw_Articles.AddedDate, ftw_Articles.AddedBy, ftw_Articles.Title,
      ROW_NUMBER() OVER (ORDER BY ReleaseDate DESC) AS RowNum
   FROM ftw_Articles INNER JOIN
         ftw_Categories ON ftw_Articles.CategoryID = ftw_Categories.CategoryID
) Articles
   WHERE Articles.RowNum BETWEEN (@PageIndex*@PageSize+1) AND ((@PageIndex+1)*@PageSize)
   ORDER BY AddedDate DESC

Open in new window

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David H.H.LeeCommented:
Hi Aluedke,
You can use CASE function and LEFT function in order to complete the required.
Try this:
select CASE WHEN len(ftw_Articles.Title)>100 THEN left(ftw_Articles.Title,100)+'...' ELSE ftw_Articles.Title END AS ArticleTitle from ftw_Articles
Hi Aluedke

The example below uses a cutoff of 50.
DECLARE @MaxLen int;
SET @MaxLen = 50;
DECLARE @MyTable TABLE (MyField varchar(255));
INSERT INTO @MyTable values ('This is a string that is 54 characters long in total.');
INSERT INTO @MyTable values ('This string is 43 characters long in total.');
     , CASE WHEN LEN(MyField) > @MaxLen 
            THEN REVERSE(RIGHT(RIGHT(REVERSE(MyField), @MaxLen), @MaxLen - CHARINDEX(' ', RIGHT(REVERSE(MyField), @MaxLen)))) + ' ...'
            ELSE MyField END as MyTruncatedField
  FROM @MyTable;

Open in new window

Perhaphs a cleaner way would be to use a function. See code below:
-- Define a function called fn_TruncateAtLastSpace. 
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_TruncateAtLastSpace]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fn_TruncateAtLastSpace]
CREATE FUNCTION [dbo].[fn_TruncateAtLastSpace](@strInput varchar(255), @MaxLen int, @strAppendIfTruncated varchar(10))
	DECLARE @strOutput varchar(255)
	SET @strOutput = (SELECT CASE WHEN LEN(@strInput) > @MaxLen 
								  THEN REVERSE(RIGHT(RIGHT(REVERSE(@strInput), @MaxLen), @MaxLen - CHARINDEX(' ', RIGHT(REVERSE(@strInput), @MaxLen)))) + ' ...'
								  ELSE @strInput END);
	RETURN @strOutput
-- Use the function called fn_TruncateAtLastSpace. 
DECLARE @MyTable TABLE (MyField varchar(255));
INSERT INTO @MyTable values ('This is a string that is 54 characters long in total.');
INSERT INTO @MyTable values ('This string is 43 characters long in total.');
SELECT MyField, dbo.fn_TruncateAtLastSpace(MyField, 50, '...')
  FROM @MyTable;

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2005

From novice to tech pro — start learning today.