且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-19 22:25:27

您无需将文本拆分为多个部分.您确实需要确保在您 连接字符串:

You don't need to split the text into parts. You do need to make sure that truncation doesn't occur whilst you're concatenating strings:

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

If the result of the concatenation of strings exceeds the limit of 8,000 bytes, the result is truncated. However, if at least one of the strings concatenated is a large value type, truncation does not occur.

因此,请确保第一次连接使用的是大值类型(因此会产生大值类型作为结果),并且每个后续连接都应避免截断:

So, make sure that the first concatenation is working with a large value type (and thus produces a large value type as its result) and every subsequent concatenation should be saved from truncation:

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

(通过这种方式,您不必到处插入转换)

(In this way, you don't have to insert conversions everywhere)

这会产生一个错误:

declare @t nvarchar(max)

set @t = 'select LEN(''' + REPLICATE('A',3000) + REPLICATE('B',3000) + REPLICATE('C',3000) + ''')'

exec sp_executesql @t

这会产生结果 9000:

And this produces the result 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