Truncate string in SQL

Posted on 2008-11-13
Last Modified: 2012-05-05
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

Question by:Aluedke
    LVL 29

    Expert Comment

    by:David H.H.Lee
    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
    LVL 11

    Expert Comment

    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.');
    SELECT MyField
         , 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

    LVL 11

    Accepted Solution

    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


    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Join & Write a Comment

    In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
    Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
    Hi everyone! This is Experts Exchange customer support.  This quick video will show you how to change your primary email address.  If you have any questions, then please Write a Comment below!
    Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now