触发更新多个表

时间:2014-12-18 20:40:50

标签: sql-server

尝试创建一个触发器,该插件应在插入其父表时将数据插入三个表中。

Diagram

enter image description here

Table_1

enter image description here

Table_2

enter image description here

Table_3

enter image description here

Table_4

enter image description here

我的对象探险家

enter image description here

我正在尝试使用的代码块是

USE [demo1]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[autoupdate]
    ON [dbo].[Table_1]
    AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO dbo.Table_2(ONEID) 
        SELECT ONEID FROM INSERTED i
        WHERE NOT EXISTS (SELECT 1 FROM dbo.Table_2 t2 WHERE t2.ONEID = i.ONEID) 
        AND i.ONEID IS NOT NULL;

END

GO

它可以使用从Table_2获取的数据来更新ONEID。现在我如何修改它以将ONEID插入其余表格?

For Dave

INSERT INTO dbo.Table_2(ONEID)
SELECT ONEID FROM INSERTED i 
WHERE NOT EXISTS (SELECT 1 FROM dbo.Table_2 t2 WHERE t2.ONEID = i.ONEID) 
AND i.ONEID IS NOT NULL;

INSERT INTO dbo.Table_3(ONEID)
SELECT ONEID FROM INSERTED i 
WHERE NOT EXISTS (SELECT 1 FROM dbo.Table_2 t2 WHERE t2.ONEID = i.ONEID)
AND i.ONEID IS NOT NULL;

INSERT INTO dbo.Table_4(ONEID)
SELECT ONEID FROM INSERTED i 
WHERE NOT EXISTS (SELECT 1 FROM dbo.Table_2 t2 WHERE t2.ONEID = i.ONEID) 
AND i.ONEID IS NOT NULL;

1 个答案:

答案 0 :(得分:1)

像这样:

INSERT INTO dbo.Table_2(ONEID)
SELECT ONEID FROM INSERTED i 
WHERE NOT EXISTS (SELECT 1 FROM dbo.Table_2 t2 WHERE t2.ONEID = i.ONEID) 
AND i.ONEID IS NOT NULL;

INSERT INTO dbo.Table_3(ONEID)
SELECT ONEID FROM INSERTED i 
WHERE NOT EXISTS (SELECT 1 FROM dbo.Table_3 t3 WHERE t3.ONEID = i.ONEID)
AND i.ONEID IS NOT NULL;

INSERT INTO dbo.Table_4(ONEID)
SELECT ONEID FROM INSERTED i 
WHERE NOT EXISTS (SELECT 1 FROM dbo.Table_4 t4 WHERE t4.ONEID = i.ONEID) 
AND i.ONEID IS NOT NULL;