Capturing multiple error messages from a single statement inside TRY CATCH

后端 未结 3 531
醉话见心
醉话见心 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条回答
  •  抹茶落季
    2020-12-06 02:40

    Depending on your needs and the permissions of the account that you are running this script under you may be able to use DBCC OUTPUTBUFFER(@@spid).

    I came across this idea when reading Erland Sommarskog's Error Handling article. He links to a procedure spGET_ErrorMessage.

    Unfortunately this didn't quite work in my test script on SQL Server 2008 though so I'm not sure if the buffer format has changed but it might get there with a bit of tweaking!

    CREATE TABLE #foo
    (
    c INT DEFAULT(0)
    )
    ALTER TABLE #foo ALTER COLUMN c VARCHAR(10)
    
    GO
    EXEC spGET_LastErrorMessage
    

    Actual Output

    Msg 5074, Level 16, State 1, Line 2
    The object 'DF__#foo___________c__6DCC4D03' is dependent on column 'c'.
    
        Msg 4922, Level 16, State 9, Line 2
        ALTER TABLE ALTER COLUMN c failed because one or more objects access this column.
    

    Claimed Output

    errNumber            errState    errLevel    errMessage                                                                               errInstance                                                                                                                     errProcedure    errLine
    -------------------- ----------- ----------- ---------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------- --------------- -----------
    5074                 1           16          The object 'DF__#foo___________c__6DCC4D03' is dependent on column 'c'.                  MARTINHP                                                                                                                        NULL            2
    4922                 9           16          The object 'DF__#foo___________c__6DCC4D03' is dependent on column 'c'.ALTER TABL        MARTINHP 䄀䰀吀䔀刀 䌀伀䰀唀䴀一 挀 昀愀椀氀攀搀 戀攀挀愀甀猀攀 漀渀攀 漀爀 洀漀爀攀 漀戀樀攀挀琀猀 愀挀挀攀猀猀 琀栀椀         NULL            117
    

提交回复
热议问题