Search code examples
sql-serverdynamic-sqlnvarchar

SQL Server dynamic SQL size exceed 4000 chars


In SQL Server I have dynamic sql query, but the size of the query is higher than 4000 chars. Like in this post SQL Server 2012: dynamic SQL limitation ( > 4000 chars) (split) there is no problem to manage with this issue. But the problem is when I want to join string with variable. For example, this works ok:

DECLARE @sqlQuery NVARCHAR(MAX);
DECLARE @sqlQueryWhere NVARCHAR(MAX);

SET @sqlQuery =
    CONVERT(nvarchar(max),'SELECT
 .... '
EXECUTE sp_executesql @sqlQuery

But this sample doesn't work:

 DECLARE @sqlQuery NVARCHAR(MAX);
 DECLARE @sqlQueryWhere NVARCHAR(MAX);

SET @sqlQueryWhere = CONVERT(nvarchar(max),' 1 = 1 ' )

SET @sqlQuery =
        CONVERT(nvarchar(max),'SELECT
     .... ' + @sqlQueryWhere + ' group by ... '
EXECUTE sp_executesql @sqlQuery

Solution

  • Your sample is wrong because you are converting after concatenation

    Your concatenation is a series of short string that can't go above 4000 characters. That is. using + won't magically make the string more than 4000 characters

    I described it in my answer here

    This will work:

    DECLARE @sqlQuery NVARCHAR(MAX);
    DECLARE @sqlQueryWhere NVARCHAR(MAX);
    DECLARE @sqlQueryBase NVARCHAR(MAX);
    DECLARE @sqlQueryGroupyBy NVARCHAR(MAX);
    
    SET @sqlQueryWhere = N' 1 = 1 ' --already NVARCHAR(MAX)
    SET @sqlQueryBase = N'SELECT
         .... '
    SET @sqlQueryGroupyBy = N' group by ... '
    
    SET @sqlQuery = CONCAT(@sqlQueryBase, @sqlQueryWhere @sqlQueryGroupyBy)
    
    EXECUTE sp_executesql @sqlQuery