How to debug a T-SQL trigger?

前端 未结 4 1551
清歌不尽
清歌不尽 2021-02-03 23:15

I have a table t, which has an \"after insert\" trigger called trgInsAfter. Exactly how do i debug it? i\'m no expert on this, so the question and steps performed might look sil

4条回答
  •  渐次进展
    2021-02-03 23:45

    For whatever reason I couldn't get @Damien_The_Unbeliever's solution to work. At least, not on a trigger attached to a table. When I did a Step Into it just executed the query every time without stepping into the trigger.

    Then I noticed in the comments of that approach that you can't see any of the table values anyway.

    So......

    I ended up creating a generic Debug Table.

    USE [Your_DB]
    GO
    
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    SET ANSI_PADDING ON
    GO
    
    CREATE TABLE [dbo].[Debug_Table](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [Name] [varchar](60) NOT NULL,
        [Value] [sql_variant] NULL,
        [Description] [varchar](max) NULL,
        [Captured] [datetime] NOT NULL
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
    GO
    
    SET ANSI_PADDING OFF
    GO
    

    And then in my trigger I did something like this...

    DECLARE @ItemNum nvarchar(128)
    SELECT  @ItemNum = Item_Number FROM inserted
    
    DECLARE @debugOn as bit = 1
    -- Debug
        IF @debugOn = 1
        BEGIN
            INSERT INTO Debug_Table (Name, Value, Description, Captured)
            VALUES ( 'Item Number', @ItemNum, 'The item number from the inserted table in tr_VaultItemIterations_ZCode_Monitor.', GETDATE())
        END;
    -- End Debug
    

    After the trigger fired from the table I could view any of the variables I inserted to the Debug_Table.

    After you're done debugging you could could easily turn off debugging inserts by changing the @debugOn variable to 0 in case you ever need to debug again in the future; or just remove the debug code altogether.

提交回复
热议问题