I am having a rather strange problem when building a dynamic query in SQL Server. I declare a variable of NVARCHAR(MAX) type, and build some queries into it, running them later with sp_executesql.
One or two of these queries are so large that they surpass the 4000 char limit that, supposedly, NVARCHAR(MAX) overcomes. However, I still am having the classic problem of storing the whole query inside the variable!
I read online documentation and many of them suggests we can store upto 2 GB of data into NVARCHAR(MAX) variable but I don't know why it is not storing more than 4000 characters into the variable.
Any help will be appreciated.
EDIT - Added Sample Code
DECLARE @qry NVARCHAR(MAX);
SET @qry = N'SELECT * FROM Table1 t1' + N'INNER JOIN Table2 t2 ON t1.Col1 = t2.Col2' + N'INNER JOIN Table3 t3 ON t1.Col1 = t2.Col3'
EXEC sp_executeSQL @qry
Above is just a sample query with fewer characters, my actual query build-up is containing around 6000 characters.