0

玩触发器;这个概念听起来很简单,但一直停留在为什么我的插入表是空的,正如调试器和打印语句所证明的那样。

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

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 
4

1 回答 1

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 
于 2012-07-11T19:01:31.107 回答