Home » excel » How can I truncate results after a certain amount of characters in SQL Server

How can I truncate results after a certain amount of characters in SQL Server

Posted by: admin May 14, 2020 Leave a comment


I’m trying to truncate results after 32,759 characters, since that is the character limit in excel and that’s where my results will be pasted.

Two method I’ve tried so far:

CONVERT(varchar(max), substring(comment,1,37259)) as [Comment]
CONVERT(varchar(max), ( substring(comment,1,8000) + substring(comment,8001,16000)...)) as [comment]

Edit: It seems like the data isn’t getting into the varchar(max) as it’s returning results with only 8000 characters. This is part of a select statement. I have no problem getting results over 32759 characters, it’s just that they run into the next line when pasting into excel – which is why I’m trying to truncate.

How to&Answers:

All this stuff shouldn’t be necessary. If comment is varchar(max), you should be able to say:

SUBSTRING(comment, 1, 37259)

If it is text or ntext then you need to convert it first:


(Which is obviously much tidier than your solution.)


Figured it out, might as well toss this up in case someone else runs into this problem:

convert(varchar(max), ( cast(substring(comment,1,8000) as varchar(max)) +     
cast(substring(comment,8001,8000) as varchar(max)) + 
cast(substring(comment,16002,8000) as varchar(max)) + 
cast(substring(comment,24003,8000) as varchar(max)) + 
cast(substring(comment,32004,755) as varchar(max)) )) as 

It looks like by not casting each piece the data size is being set to a data size/type that will accommodate all pieces.