Search code examples
sql-server-2012nvarchar

Does nvarchar(max) only allow 4000 characters?


In the query below nvarchar(max) seems to truncate at 4000 characters. That seems contrary to the answer here which says "Since NVARCHAR uses 2 bytes per character, that's approx. 1 billion characters."

DECLARE @test NVARCHAR(MAX)
DECLARE @i INT
SET @i=0
set @test=cast('x' as nvarchar(max))

while(@i<6000)
begin
set @test= (@test+ cast('x' as nvarchar(max)))
set @i=@i+1

end

print @TEST--has only 4000 characters

Solution

  • Sorry, just found out that this is a limitation of the message screen in Sql server management studio. The code below shows correct results

    DECLARE @test NVARCHAR(MAX)
    DECLARE @i INT
    SET @i=0
    set @test=cast('x' as nvarchar(max))
    
    while(@i<6000)
    begin
    set @test= (@test+ cast('x' as nvarchar(max)))
    set @i=@i+1
    
    end
    
    print len(@TEST)--6001