Tuesday, April 11, 2017

Sample SQL Server Function to Truncate a string

Below is the sample SQL Server function to Truncate a string to the given number of characters.

If the string is smaller than the given limit, it is returned as-is; otherwise, it is truncated to 3 characters less than the given limit, and '...' is placed at its end..

SQL Server Function :
  1. create function [dbo].[TruncateString]
  2. (
  3. @Str varchar(max),
  4. @MaxLength int
  5. )
  6. returns varchar(8000)
  7. as begin
  8. if @MaxLength is null or @MaxLength < 3 set @MaxLength = 3
  9. if @MaxLength > 8000 set @MaxLength = 8000
  10.  
  11. return case
  12. when datalength(@Str) <= @MaxLength then @Str
  13. else left(@Str, @MaxLength - 3) + '...'
  14. end
  15. end

No comments:

Post a Comment