这是一个例子:
USE DatabaseName;
GO
IF OBJECT_ID ('Sch.UpdateSecondTable', 'TR') IS NOT NULL
DROP TRIGGER Sch.UpdateSecondTable;
GO
CREATE TRIGGER Sch.UpdateSecondTable
ON FirstTable
AFTER INSERT
AS
INSERT INTO SecondTable
SELECT * FROM Inserted
GO
但是,如果您想使用第一个表中插入的值更新第二个表表单,请尝试使用以下语句代替INSERT
子句:
UPDATE t2
SET t2.name = t1.name
FROM SecondTable t2
INNER JOIN inserted t1 ON t1.id = t2.id
更新:如果您只想插入第二个 tabl3e 中不存在的值。如果这些表具有相同的结构,即相同的列号和相同的数据类型。您可以使用EXCEPT
set 运算符执行此操作,如下所示:
UPDATE t2
SET t2.name = t1.name
FROM SecondTable t2
INNER JOIN
(
SELECT * FROM inserted t1
EXCEPT SELECT * FROM SECONDTABLE
) t1 ON t1.id = t2.id
如果不使用标准方法这样做:
UPDATE t2
SET t2.name = t1.name
FROM SecondTable t2
INNER JOIN
(
SELECT * FROM inserted t1
WHERE id NOT IN(SELECT id FROM SECONDTABLE)
) t1 ON t1.id = t2.id