T-SQL VARCHAR(MAX) Truncated

后端 未结 6 1607
谎友^
谎友^ 2020-12-19 01:32
DECLARE @str VARCHAR (MAX);

SELECT @str = COALESCE(@str + CHAR(10), \'\') +
       \'EXECUTE CreateDeno \' + CAST(ID AS VARCHAR) 
FROM   GL_To_Batch_Details
WHERE           


        
6条回答
  •  时光说笑
    2020-12-19 02:23

    I also wanted to see what I was sending to Exec, and was confused by the PRINT limit. Had to write a proc to print in chunks.

    CREATE PROCEDURE [dbo].[KFX_PrintVarcharMax] 
        @strMax varchar(max)
    AS
    BEGIN
        SET NOCOUNT ON;
    
        DECLARE 
            @index int = 0,
            @start int = 1,
            @blkSize int = 2000;
    
    
        WHILE @Start < LEN(@strMax)
        BEGIN
            IF @start + @blkSize >= LEN(@strMax)
            BEGIN
                -- If remainder is less than blocksize print the remainder, and exit.
                PRINT SUBSTRING(@strMax, @start, @blkSize)
                BREAK;
            END
            -- Else find the next terminator (beyond the blksize)
            SET @index = CHARINDEX(CHAR(10), @strMax, @start + @blkSize);
            if @index >= @start
            BEGIN
                PRINT SubString(@strMax, @start, @index - @start + 1)
                SET @start = @index + 1;
                SET @blkSize  = CASE WHEN @start + 2000 < LEN(@strMax) THEN 2000 
                                ELSE LEN(@strMax) - @start + 1 END
            END
            ELSE
            BEGIN
                -- No char(10) found.  Just print the rest.
                PRINT SUBSTRING(@strMax, @start, LEN(@strMax))
                BREAK;
            END 
        END
    
    END
    

提交回复
热议问题