sp_executesql or exec(@var) is too long. Maximum length is 8000

angel picture angel · Oct 2, 2013 · Viewed 10.1k times · Source

I have large queries so i cant use linked server in production by rules. i pass a varchar(max) which this has more than 8000 characters.

but sp_executesql does not support more than 8000 characters then how can i execute my string?

Answer

My Stack Overfloweth picture My Stack Overfloweth · Oct 2, 2013

nvarchar(max) should work on SQL Server 2008 or later.

Does this work?:

declare @sql nvarchar(max)
set @sql = N'select' + CONVERT(NVARCHAR(MAX),REPLICATE(' ', 8000)) + ' ''Above 8000 character limit test'''
exec sp_executesql @sql

If you're using a version before that, you may need to split the query into multiple variables:

How to use SQL string variable larger than 4000 character in SQL server 2005 Stored Procedure?