I have a table containing a large number of rows. Each row has 2 columns which I need to use – the first is some HTML formatting and the second is the text. I need to concatenate all these rows into a single string value so that I can e-mail this massive string. Due to the large number of rows I can’t use a VARCHAR variable – I have to use text. The current solution is to use a cursor to read all the rows and then insert into a temporary table with a single column of type text and then simply append to the single row in that table.
The problem is that the string seems to get cutoff after about 33000 characters. I have absolutely no idea why this is happening.
EDIT: I have taken some of the advice from the answers given here and changed the solution to use VARCHAR(MAX). However I’m still getting cutoff, but in a very odd way. It doesn’t seem like the variable is getting an overflow, it’s simply not appending all the values.
DECLARE @Result VARCHAR(MAX)
SET @Result = ''
SELECT @Result = @Result + ltrim(isnull(format,'')) + ' ' + text + '<BR></TD></TR><TR><TD CLASS="GEN" align="left" BGCOLOR="#E9ECFD">'
FROM SomeTable
The really odd bit is that if I take out the bit where I’m appending all that html at the end of the line, it all works fine. I’ve even inserted everything into a tmp table first and then did this concatenation select – still no luck. The tmp table contains the correct values (including the html), but the final variable doesn’t.
From SQL Server 2005, there is support for VARCHAR(MAX) and NVARCHAR(MAX) to handle large strings over 8000 (4000 for NVARCHAR) characters, up to ~2GB. So as of 2005, you should be looking to use those instead of TEXT/NTEXT which will be being deprecated in a future version of SQL Server.
This support for MAX makes things easier than having to deal with TEXT, so give that a whirl.