2012-07-11 117 views
0

玩触发器;这个概念听起来很容易,但坚持为什么我的插入表是空的,调试器和打印语句都证明了这一点。为什么“更新后”触发器的INSERTED表为空?

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

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

近在咫尺,我看到了这个问题。我们已经将名为“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 
+0

看起来还是越野车,它会为多行更新失败,除非它们都具有相同的'@ NewComments' – 2012-07-11 19:05:10

+0

同意,这里很多车的事情......显然,所有授权更新是在一个行在时间基础上。 – NealWalters 2012-07-11 21:16:43