我需要构建一个触发器来执行复杂的插入任务

时间:2012-08-03 16:33:50

标签: sql-server

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

我需要一个触发器来将某些信息发送到表格以转移到另一个组。但是,只有在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

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

2 个答案:

答案 0 :(得分:0)

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

Use the inserted and deleted Tables

  

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

     

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

     
      
  • 扩展表之间的引用完整性。
  •   
  • 在视图底层的基表中插入或更新数据。
  •   
  • 测试错误并根据错误采取措施。
  •   
  • 找出数据修改前后表的状态之间的差异,并根据差异采取措施。
  •   

答案 1 :(得分: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