SQL Server 2008 Nvarchar(Max) concatenation - Truncation issue

有些话、适合烂在心里 提交于 2019-12-10 15:23:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!