问题
Can someone please explain why this is happening on SQL Server 2008:
declare @sql Nvarchar(max);
set @sql =N'';
select @sql = @sql +replicate('a',4000) + replicate('b', 6000);
select len(@sql)
Returns: 8000
Multiple sites suggest that as long as first variable is of type NVARCHAR(MAX), truncation should not occur, but it still does.
回答1:
Because 'a'
and 'b'
are not of type NVARCHAR(MAX)
Like this, it should work:
declare @sql Nvarchar(max),
@a nvarchar(max),
@b nvarchar(max);
select @sql =N'', @a = N'a', @b = N'b';
select @sql = @sql +replicate(@a,4000) + replicate(@b, 6000);
select len(@sql)
This is the link to Microsoft's REPLICATE function information: https://msdn.microsoft.com/en-us/library/ms174383.aspx
In there, it says:
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.
回答2:
As to why, I don't know. I just know NVARCHAR likes to cut off at 8000 unless you cast things to NVARCHAR(MAX) or you can use CONCAT():
DECLARE @sql Nvarchar(max);
SELECT @sql = CONCAT(@sql,replicate('a',4000),replicate('b', 6000)) --do it this way
--SELECT @sql = CAST(replicate('a',4000) AS NVARCHAR(MAX)) + CAST(replicate('b', 6000) AS NVARCHAR(MAX)) --or this way
Both result in a LEN(@sql) of 10,000
来源:https://stackoverflow.com/questions/29931706/sql-server-2008-nvarcharmax-concatenation-truncation-issue