尝试创建一个触发器,该插件应在插入其父表时将数据插入三个表中。
Diagram
Table_1
Table_2
Table_3
Table_4
我的对象探险家
我正在尝试使用的代码块是
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;
答案 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;