Reputation: 8816
I can use the following code for tiny little queries:
DECLARE @sql VARCHAR(8000)
SET @sql = 'SELECT * FROM myTable'
Exec @sql
The above method is very useful in order to maintain large amounts of code, especially when we need to make changes once and have them reflected everywhere.
My problem is my query (it's only one single query) that I want to feed into the @sql variable uses more than 25 table joins, some of them on temporary table variables, incorporates complex operations and it is hence much more than 8000 characters long.
I wished to use TEXT data type to store this query, but MSDN shows a warning message that Microsoft is planning to remove Text, NText and Image data types from their next versions. I wish my code to run in future too.
I thought of storing this query in a separate file, but as it uses joins on table variables and other procedure-specific parameters, I doubt if this is possible.
Kindly tell me a method to store a large query into a variable and execute it multiple times in a procedure.
Upvotes: 27
Views: 121419
Reputation: 19422
If you have Unicode/nChar/nVarChar values you are concatenating, then SQL Server will implicitly convert your string to VarChar(8000), and it is unfortunately too dumb to realize it will truncate your string or even give you a Warning that data has been truncated for that matter!
When concatenating long strings (or strings that you feel could be long) always pre-concatenate your string building with CAST('' as nVarChar(MAX)) like so:
SET @Query = CAST('' as nVarChar(MAX))--Force implicit conversion to nVarChar(MAX)
+ 'SELECT...'-- some of the query gets set here
+ '...'-- more query gets added on, etc.
What a pain and scary to think this is just how SQL Server works. :(
I know other workarounds on the web say to break up your code into multiple SET/SELECT assignments using multiple variables, but this is unnecessary given the solution above.
For those who hit a 4000 character max, it was probably because you had Unicode so it was implicitly converted to nVarChar(4000).
Warning:
You still Cannot have a Single Unbroken Literal String Larger than 8000 (or 4000 for nVarChar).
Literal Strings are those you hard-code and wrap in apostrophe's.
You must Break those Strings up or SQL Server will Truncate each one BEFORE concatenating.
I add ' + '
every 20 lines (or so) to make sure I do not go over.
That's an average of at most 200 characters per line - but remember, spaces still count!
Explanation:
What's happening behind the scenes is that even though the variable you are assigning to uses (MAX), SQL Server will evaluate the right-hand side of the value you are assigning first and default to nVarChar(4000) or VarChar(8000) (depending on what you're concatenating). After it is done figuring out the value (and after truncating it for you) it then converts it to (MAX) when assigning it to your variable, but by then it is too late.
Upvotes: 46
Reputation: 173
If what you are trying to accomplish is to do this in Management Studio, the script below might help.
DECLARE @Len INT = 5
DECLARE @Str VARCHAR(MAX) = '1111122222333334444455555'
DECLARE @TmpStr VARCHAR(MAX)
DECLARE @Return TABLE (RetStr VARCHAR(MAX))
WHILE(LEN(@Str) > 0)
BEGIN
SET @TmpStr = LEFT(@Str, @Len)
IF(LEN(@Str) > @Len)
SET @Str = RIGHT(@Str, LEN(@Str) - @Len)
ELSE
SET @Str = ''
INSERT INTO @Return SELECT @Str
END
SELECT * FROM @Return
There @Len
should be 8000, as this is the maximum length Management Studio shows. @Str
is the text that is longer than 8000 characters.
Upvotes: 0
Reputation: 272
Before print convert into cast and change datatype.
PRINT CAST(@sql AS NTEXT)
Now, try it.
Upvotes: 0
Reputation: 677
I had the same issue. I have a SQL which was more than 21,000 characters. For some reason,
Declare @SQL VARCHAR(MAX)
EXEC(@SQL)
would come up with several issues
I had to finally split it up in multiple variables equally and then it worked.
Declare @SQL1 VARCHAR(MAX) = 'First Part'
Declare @SQL2 VARCHAR(MAX) = 'Second Part'
Declare @SQL3 VARCHAR(MAX) = 'Third Part'
Declare @SQL4 VARCHAR(MAX) = 'Fourth Part'
Set @SQL= @SQL1 + @SQL2 + @SQL3 + @SQL4
EXEC(@SQL)
Upvotes: 1
Reputation: 103
I have been having the same problem, with the strings being truncated. I learned that you can execute the sp_executesql statement multiple times.
Since my block of code was well over the 4k/Max limit, I break it out into little chunks like this:
set @statement = '
update pd
set pd.mismatchtype = 4
FROM [E].[dbo].[' + @monthName + '_P_Data] pd
WHERE pd.mismatchtype is null '
exec sp_executesql @statement
set @statement = 'Select * from xxxxxxx'
exec sp_executesql @statement
set @statement = 'Select * from yyyyyyy '
exec sp_executesql @statement
end
So each set @Statement can have the varchar(max) as long as each chunk itself is within the size limit (i cut out the actual code in my example, for space saving reasons)
Upvotes: 0
Reputation: 1
ALTER PROCEDURE [dbo].[spGetEmails]
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
declare @p varbinary(max)
set @p = 0x
declare @local table (col text)
SELECT @p = @p + 0x3B + CONVERT(varbinary(100), Email)
FROM tbCarsList
where email <> ''
group by email
order by email
set @p = substring(@p, 2, 10000000)
insert @local values(cast(@p as varchar(max)))
select col from @local
END
Upvotes: 0
Reputation: 116
You should read the answer of this post which explains extremely well the situation : SQL NVARCHAR and VARCHAR Limits
nvarchar(x)
varchar(y)
nvarchar(max)
which can store up to 2GB.Problem is that nvarchar(max) + varchar(y) = nvarchar(max) + nvarchar(4000)
; SQL will convert your varchar(y)
into nvarchar(y)
or nvarchar(4000)
if y is greater than 4000 and lesser than 8000, truncating your string !
Upvotes: 3
Reputation: 11
There is no solution for this along the way that you are doing it. 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.
At best with a MsSql version the max size of a variable is 8000 characters on the latest version as of when this was typed. So if you are dealing with a string of say 80,000 characters. You can parse the data into ten variables of 8000 characters each (8000 x 10 = 80,000) or you can chop the variable into pieces and put it into a table say LongTable (Bigstring Varchar(8000)) insert 10 rows into this and use an Identity value so you can retrieve the data in the same order.
The method you are trying will not work with MsSql currently.
Another obscure option that will work but is not advisable is to store the variable in a text file by using command shell commands to read/write the file. Then you have space available to you beyond 8000 characters. This is slow and less secure than the other methods described above.
Upvotes: 1
Reputation: 2270
DECLARE @sql VARCHAR(max)
SET @sql = 'SELECT * FROM myTable'
Exec @sql
Note:
Print(@sql)
only show the first 8000 characters!
Upvotes: 8
Reputation: 5615
Well I ran to this before (in SQL 2005) and I can tell you that you have two options:
1 - Use the sys.sp_sqlexec stored procedure that can take a param of type text (IMO this is the way to go). Don't mind the warning. In SQL 2008 ntext is still supported, and if you do the varchar(max) thingy there, it will work. So basically, if you have 2008, both the text solution and the varchar(max) will work, so you will have time to change it =-). In 2012 though, only the varchar(max) will work, therefore you'll have to change it before upgrading.
2- (This is what I did at first) Check THIS post: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=52274 and do what user "Kristen" says. Worked like a charm for me. Don't forget to pre-set them to an empty string. If you understood my post you know by now that in SQL 2008 or newer is silly to do this.
Upvotes: 2
Reputation: 3625
Problem is because your string has limit 8000 symbols by default. To prevent this you should convert it to (N)VARCHAR(MAX)
DECLARE @sql VARCHAR(8000)
SET @sql = CAST('SELECT * FROM myTable' AS VARCHAR(MAX))
--Check length of variable
PRINT 'Length is: '+CAST(LEN(@sql) AS VARCHAR)+ 'symbols'
Exec @sql
Upvotes: 4
Reputation: 6021
If you are on SQL Server 2008 or newer you can use VARCHAR(MAX)
DECLARE @sql VARCHAR(MAX)
Upvotes: 18