0

编辑-这是从原始问题扩展而来的。

我需要一个触发器来将某些信息发送到要转移到另一个组的表。然而,只有在 T2 上由 C4 确定的某一类数据在更新时需要传输。

create trigger Trig on T2
after Insert, update, delete
if update(C3) --DETERMINES THAT RECORD HAS BEEN UPDATED IN A MANNER THAT NEEDS TO BE  
              TRANSFERRED     
begin
if C4 != 9 return --DETERMINES IF RECORD NEEDS TO BE TRANSFERRED
else
insert P1 --BEGINS PUTTING INFORMATION INTO THE ABLE THAT IS TRANSFERRED
(C1, C2, C3)
select T1.C2, T1.C3, T2.C3 --INFORMATION THAT NEEDS TO BE TRANSFERRED
FROM T1, T2
WHERE T1.C1 = T2.C2 --T1.C1 IS A UNIQUE PRIMARY KEY THAT CONNECTS ROW IN T1 TO ROW
                      IN T2
END
GO

这是完整的测试代码。实际代码将涉及更多不同名称的列。所有表数据类型都相同。谢谢。

4

2 回答 2

0
create trigger Trig on T2
after insert, update, delete
as
 -- So that @@rowcount does not get affected by trigger code
    set NoCount on
 -- If c3 column participated in update (it most certainly did in insert)
    if update(C3)
    begin
     -- Insert or update triggered this operation
        if exists (select *
                     from Inserted)
        begin
            insert into P1 (C1, C2, C3)
            select T1.C2, T1.C3, T2.C3 --INFORMATION THAT NEEDS TO BE TRANSFERRED
            from T1
         -- Inserted is a pseudotable holding inserted/updated data
            inner join inserted T2
            on T1.C1 = T2.C2
            where T2.C4 <> 9 --DETERMINES IF RECORD NEEDS TO BE TRANSFERRED
        end
        else
     -- Separate insert for deleted records
     -- To simplify inserting additional info for deleted records only
        begin
            insert into P1 (C1, C2, C3)
            select T1.C2, T1.C3, T2.C3 --INFORMATION THAT NEEDS TO BE TRANSFERRED
            from T1
         -- deleted is a pseudotable holding deleted/updated data
            inner join deleted T2
            on T1.C1 = T2.C2
            where T2.C4 <> 9 --DETERMINES IF RECORD NEEDS TO BE TRANSFERRED
        end
    end
于 2012-08-03T22:35:46.343 回答
0

您可以访问INSERTED触发器中的表以获取c4列的值,但如果您可以向我们提供有关您尝试解决的问题的更多信息,也许我们可以建议比触发器更好的替代方案。

使用插入和删除的表

DML 触发器语句使用两个特殊表:已删除表和已插入表。SQL Server 自动创建和管理这些表。您可以使用这些临时的、驻留在内存中的表来测试某些数据修改的效果并为 DML 触发操作设置条件。您不能直接修改表中的数据,也不能对表执行数据定义语言 (DDL) 操作,例如 CREATE INDEX。

在 DML 触发器中,插入表和删除表主要用于执行以下操作:

  • 扩展表之间的参照完整性。
  • 在视图基础的基表中插入或更新数据。
  • 测试错误并根据错误采取措施。
  • 找出数据修改前后表状态之间的差异,并根据该差异采取行动。
于 2012-08-03T16:42:00.367 回答