I have a variable
which has SQL
string stored in it and am executing it through exec()
Declare @sql varchar(max)
set @sql = Concat('select...',@var,'..') -- large string
exec (@sql)
but am getting error saying
Incorrect syntax near sometext
It is because the variable @sql
cannot hold the entire string. So I fixed by splitting the string into two different variables and executed it
Declare @sql1 varchar(max),@sql2 varchar(max)
set @sql1 = 'select...'
set @sql2 = ' from sometable join....'
exec (@sql1+@sql2)
I checked the data length of @sql1+ @sql2
Select Datalength(@sql1+ @sql2)
It returned 14677
Now question is why varchar(max)
cannot store 14677
bytes of information? When the documents says it can store upto 2GB
of data
CHAR, VARCHAR, and VARCHAR(MAX) CHAR columns should be used for columns that vary little in length. String values that vary significantly in length and are no longer than 8,000 bytes should be stored in a VARCHAR column. If you have huge strings (over 8,000 bytes), then VARCHAR(MAX) should be used.
The reason this happens is that SQL Server doesn't want to store something as VARCHAR(MAX) if none of the variable's components are defined as VARCHAR(MAX).
DO NOT use VARCHAR(MAX) just because it can be. Use it only if the data to be stored can be more than 8,000 bytes.
MsSql as of 2012 supports Ntext for example that allows you to go beyond 8000 characters in a variable. The way to solve this is to make multiple variables or multiple rows in a table that you can iterate through.
It is probably this you are running against:
DECLARE @part1 VARCHAR(5000)=REPLICATE('a',5000);
DECLARE @part2 VARCHAR(5000)=REPLICATE('a',5000);
SELECT DATALENGTH(@part1),DATALENGTH(@part2),DATALENGTH(@part1+@part2);
The result is 5000,5000,8000
If one of the summands is a MAX
type, you'll get the expected result
SELECT DATALENGTH(@part1),DATALENGTH(@part2),DATALENGTH(CAST(@part1 AS VARCHAR(MAX))+@part2);
The result is 5000,5000,10000
This is often seen in connection with
VARCHAR(8000)
as former max lengthCONCAT
SELECT DATALENGTH(@part1),DATALENGTH(@part2),DATALENGTH(CONCAT(@part1,@part2));
SELECT DATALENGTH(@part1),DATALENGTH(@part2),DATALENGTH(CONCAT(CAST(@part1 AS VARCHAR(MAX)),@part2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With