SQL-更新/插入后触发选择进入

时间:2018-11-13 11:47:31

标签: sql sql-server tsql database-trigger

我有一个名为Audit_Data的表,并且不时会有更新。每个更新都包含约300行(每行约20列),并且同一更新中的所有行都共享相同的Audit_ID

我有一个选择,只提取与我相关的数据。基本上将 300x20 字段数据转换为一行数据。
有没有办法创建SQL触发器,该触发器将对更新后的Audit_Data表执行选择,并将所选数据插入名为Audit_Final的表中?

这是我用来提取相关数据的select语句:

SELECT main.Audit_ID
        ,main.Item_19
        ,main.Item_1
        ,main.Item_7
        ,main.Item_8
        ,Item_17
        ,main.Item_13
        ,macaddr.Item_2
        ,macaddr.Item_16
        ,t1.Item_1
FROM dbo.[Audit_Data] AS main
    LEFT JOIN
    (
        SELECT Audit_ID, Item_2, Item_16
        FROM dbo.[Audit_Data] AS macaddr
        WHERE 
        (Item_2 NOT LIKE 'Hyper-V%')
        AND (Item_17 = 'connected') 
        AND (Item_18 IN ('10000Mbps', '1000MBps') OR ITEM_9 IS NOT NULL AND ITEM_10 IS NOT NULL)
        AND (Item_18 != '100Mbps')
    ) macaddr ON main.Audit_ID = macaddr.Audit_ID
    LEFT JOIN
    (
        SELECT Audit_ID, Category_ID, Item_1, Record_ordinal
        FROM dbo.[Audit_Data] AS t1
        WHERE 
        Item_1 = 'Automatyczna konfiguracja sieci przewodowej' OR Item_1 = 'dot3svc' OR Item_1 = 'Wired AutoConfig'
        AND Item_3 = 'Running'
        AND Category_ID = '4100'
    ) t1 ON main.Audit_ID = t1.Audit_ID
WHERE 
main.Record_Ordinal = '2'
ORDER BY main.Audit_ID

1 个答案:

答案 0 :(得分:0)

根据作者的评论,这是必需的:

CREATE TRIGGER [TR_Audit_Data] ON [Audit_Data]
AFTER UPDATE
AS
 BEGIN
 INSERT INTO [Audit_Final](cloumn_1, colum_2, ... all columns you have on target table)
 /*
  Paste your select query here
 */
END