SQL Server 2012: 动态 SQL 限制 ( > 4000 个字符) (拆分)



我在存储过程中有这个动态 SQL:

Declare @template nvarchar(max)
Declare @publishdetails nvarchar(max)
set @publishdetails= ',B.[PublishedBy]=suser_name(),
B.[PublishedDate]=GETDATE() '
set @template='if NOT EXISTS(select * from ' +@DestinationDB+ '.[CLs] where id='+ str(@slid)+') 
insert into  ' +@DestinationDB+ '.CLs (id,slid,slversion) VALUES ( '+ str(@id)+','+ str(@slid)+','+str(@slversion)+')
update  B set 
B.[Clientid]=A.clientid,
--.........
B.[CreatedDate] = A.CreatedDate,
B.[ModifiedDate] = A.ModifiedDate,
B.[CreatedBy] = A.CreatedBy,
B.[ModifiedBy] = A.ModifiedBy '+@publishdetails+ --Added publishdetails
'FROM  ' + @SourceDB + '.[CLs] as A, '+ @DestinationDB+ '.[CLs] as B
where A.slversion = '+ str(@slversion)+' and A.id='+str(@slid) + 'B.slversion = '+ str(@slversion)+' and B.id='+str(@slid)
print 'template is: ' + @template
exec sp_Executesql @template

exec sp_Executesql @template正在执行时,它会失败。因为@template> 4000 个字符并且被截断。如何将其拆分为块并以正确的方式执行?

您不需要将文本拆分为多个部分。您确实需要确保在连接字符串时不会发生截断:

如果字符串串联的结果超过 8,000 字节的限制,则结果将被截断。但是,如果串联的字符串中至少有一个是大值类型,则不会发生截断。

因此,请确保第一个串联使用大值类型(因此生成一个大值类型作为其结果),并且每个后续串联都应避免截断:

set @template=CONVERT(nvarchar(max),'if NOT EXISTS(select * from ' ) + @DestinationDB + ...

(这样,您不必在任何地方插入转换)


这将生成一个错误:

declare @t nvarchar(max)
set @t = 'select LEN(''' + REPLICATE('A',3000) + REPLICATE('B',3000) + REPLICATE('C',3000) + ''')'
exec sp_executesql @t

这会产生结果 9000:

declare @t nvarchar(max)
set @t = CONVERT(nvarchar(max),'select LEN(''') + REPLICATE('A',3000) + REPLICATE('B',3000) + REPLICATE('C',3000) + ''')'
exec sp_executesql @t

我建议使用这种方法:

Declare @template nvarchar(max) = N''
set @template = @template +N'.... -- Or SELECT instead of SET

更新#1

我在测试数据库上运行这个简单的查询:

DECLARE @query nvarchar(max) = N'',
@i int = 1
WHILE 1000 > @i
BEGIN
SET @query = @query + N'SELECT @@version;'
SET @i = @i+1
END
SELECT LEN (@query)
EXEC sp_executesql @query

我得到了长度为 16983 个字符的批次。执行顺利 - 没有截断。我想问题出在@SourceDB + '.[CLs]@DestinationDB+ '.[CLs]表中。在某个地方,您得到了数据截断。

尝试PRINT查询并手动运行它。

最新更新