How to store a string var greater than varchar(max)?

后端 未结 1 810
无人及你
无人及你 2020-12-09 09:09

I\'m trying to do this:

DECLARE @myVar VARCHAR(MAX)
Loop with cursor
select @myVar = @myVar + bla bla bla
end loop

When the loop ends, @myV

相关标签:
1条回答
  • 2020-12-09 09:50

    Seriously - VARCHAR(MAX) can store up to 2 GB of data - not just 8000 characters.....

    Try this:

    DECLARE @myVar VARCHAR(MAX) = ''
    
    DECLARE @ix INT = 1
    
    WHILE @ix < 1000
    BEGIN
        set @myVar = @myVar + CAST('bla bla bla' AS VARCHAR(MAX))
        SET @ix = @ix + 1
    END
    
    SELECT DATALENGTH(@myvar)
    

    This will return a value higher than 8000 characters after 1000 iterations.

    The point is: if you're using varchar(max), you need to make sure to always cast all your strings to varchar(max) explicitly - as I did in this example. Otherwise, SQL Server will fall back to "regular" varchar processing, and that's indeed limited to 8000 characters....

    0 讨论(0)
提交回复
热议问题