对于以 nvarchar 为参数的内置函数,如果提供的值为 varchar,该值仍将转换为 nvarchar(4000)

For built-in functions that take nvarchar as a parameter, if the supplied value is varchar, the value is still converted to nvarchar(4000)

有关 differences between compatibility level 80 and lLevel 90 的 MS 文档说的是兼容级别 90:

"For built-in functions that take nvarchar as a parameter, if the supplied value is varchar, the value is still converted to nvarchar(4000). However, if a larger value is passed, SQL Server 2008 generates an error."

但是,当我在 SQL Server 2008 R2 中尝试时,它总是被默默地截断:

DECLARE @SQL VARCHAR(8000)

SET @SQL = REPLICATE(N'A', 9000) -- It's return 4000

SELECT LEN(@SQL)

您的单字符文字字符串仍然是 nvarchar,并且 声明为 MAX。根据 documentation:

If string_expression is not of type varchar(max) or nvarchar(max), REPLICATE truncates the return value at 8,000 bytes. To return values greater than 8,000 bytes, string_expression must be explicitly cast to the appropriate large-value data type.

因此您有一个 nvarchar(1) 被复制了 9,000 次。一旦您有 4,000 个字符,您就有 8,000 个字节,因此达到了限制。如果你想要 8,000 个字符,你需要这样做:

DECLARE @SQL varchar(8000);

SET @SQL = REPLICATE(CONVERT(nvarchar(MAX), N'A'), 9000); 

SELECT LEN(@SQL); --Returns 8,000

编辑:以上也是 returns 截断值,没有错误,因为这也是 documented:

When converting character or binary expressions (binary, char, nchar, nvarchar, varbinary, or varchar) to an expression of a different data type, the conversion operation could truncate the output data, only partially display the output data, or return an error. These cases will occur if the result is too short to display. Conversions to binary, char, nchar, nvarchar, varbinary, or varchar are truncated, except for the conversions shown in the following table.