Capturing multiple error messages from a single statement inside TRY CATCH

后端 未结 3 533
醉话见心
醉话见心 2020-12-06 01:52

I am running a batch of statements on several columns and tables and want to retrieve information on what errors occur.

The statement is a type change (varchar to nv

3条回答
  •  Happy的楠姐
    2020-12-06 02:43

    MikeCov has answered this, but I didn't want to trust the future documentation. The future is now, so I tested this and can confirm that THROW does indeed return all the error messages.

    You can reproduce this with the below script. Run each section between the comments one at a time to see the output.

    /*Create tables */
    
    CREATE TABLE dbo.test 
    (
    columna int primary key
    )
    GO
    
    CREATE TABLE dbo.test2
    (
    columnb int 
    )
    GO
    
    /*Create foreign key between these tables*/
    ALTER TABLE dbo.test2  WITH CHECK ADD  CONSTRAINT [FK_test_to_test] FOREIGN KEY(columnb)
    REFERENCES dbo.test  (columna)
    GO
    ALTER TABLE dbo.test2 CHECK CONSTRAINT [FK_test_to_test] 
    GO
    
    /* TEST 1 - only returns the last error message */
    BEGIN TRY
        ALTER TABLE dbo.test 
        ALTER Column columna varchar
    END TRY
    BEGIN CATCH
        DECLARE  @ERROR_MESSAGE NVARCHAR(2048) = ERROR_MESSAGE()
        RAISERROR (@ERROR_MESSAGE,16,16)
    END CATCH       
    
    /* TEST 2 - Returns both messages, YAY */
    BEGIN TRY
        ALTER TABLE dbo.test 
        ALTER Column columna varchar
    END TRY
    BEGIN CATCH
        THROW;
    END CATCH       
    
    
    /* Clean up */
    DROP TABLE dbo.test2
    DROP TABLE dbo.test 
    

提交回复
热议问题