为什么INSERTED表中的“After Update”触发器为空?

时间:2012-07-11 18:58:29

标签: tsql triggers

玩触发器;这个概念听起来很简单,但坚持我的插入表为空的原因,调试器和print语句都证明了这一点。

上下文是这样的:我们想用一个键更新FlightAudit表,但我们暂时禁止更改Flight表。我们想出了“hack”,用“分隔符”在“注释”列的末尾填充键,并将其解析出来。我们正在做一个测试,看看我们是否可以在“After Update”触发器中执行我们想要的操作而不是“而不是更新”触发器。我们会在分号之前将注释解析回原始值,然后使用分号后的数据更新Audit表。

ALTER TRIGGER [dbo].[tr_Flight2_Upd_Comments] ON [dbo].[Flight2]  
AFTER UPDATE 
AS   
BEGIN  

declare @initial_trancount int = @@TRANCOUNT /* this must be at the very top */;

begin try
    /* For performance reasons */   
    SET NOCOUNT ON;  

    DECLARE @Comments varchar(100); 
    DECLARE @Type char(1);  
    DECLARE @FieldsUpdated XML;      
    DECLARE @ColumnsUpdated VARBINARY(100);  
    DECLARE @AircraftChange bit; 
    DECLARE @NumInsertedRowsForDebug int; 

    SELECT Top 1 @Comments = Inserted.Comments FROM inserted 
    SELECT @NumInsertedRowsForDebug = COUNT(*) from inserted 
-- Here is where see this issue, @Comments is null & 
    print 'Comments=' + IsNull(@Comments,'null') 
    print 'NumRows=' + convert(varchar(10),@NumInsertedRowsForDebug)

    -- Action  
    IF (UPDATE(Comments)) 
           BEGIN 
               Print 'This part works fine' 
               -- logic here removed that sets @NewComments 
               UPDATE Flight 
               SET Comments = @NewComments
               FROM Inserted, Flight2
               WHERE Inserted.FlightId = Flight2.FlightID 
           END 
etc...
END 

测试脚本:

update flight2 
   set Comments = 'Test22;DL 123420120711SLC;2011-01-01 00:00:00.0000000', 
       ShortCode = 'DL' 
   where FlightId = 'D1448AF1-1F00-41C6-B2F6-2F2EE1BACE07' 
select Comments, ShortCode, * from Flight2 

1 个答案:

答案 0 :(得分:1)

发布后不久,我看到了这个问题。我们将一个名为“Flight”的真实表格克隆到一个名为“Flight2”的测试表中。

我不确定原因,但下面的第一个UPDATE语句似乎是INSERTED表为空的原因,因为当我将其更改为第二个更新语句时,INSERTED表然后按预期工作。

UPDATE Flight 
               SET Comments = @NewComments
               FROM Inserted, Flight
               WHERE Inserted.FlightId = Flight.FlightID 

UPDATE Flight 
               SET Comments = @NewComments
               FROM Inserted, Flight2
               WHERE Inserted.FlightId = Flight2.FlightID