我有2个表说A1和A2。我想在表A1中插入新记录时以这种方式创建插入,更新和删除触发器,同样的记录应插入A2中,
当我更新或删除A1表时会发生同样的情况。
答案 0 :(得分:1)
您可以将A2与触发器的UPDATED表合并。
CREATE TRIGGER dbo.trg_A1
ON dbo.A1
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
MERGE dbo.A2 AS target
USING (SELECT * FROM INSERTED) AS source
ON (target.A1_ID= source.A2_ID)
WHEN MATCHED THEN
UPDATE SET Col1 = source.Col1,
Col2 = source.Col2,
.
.
.
WHEN NOT MATCHED THEN
INSERT (Col1,Col2,Col3....)
VALUES (source.Col1, source.Col2, source.Col3....)
WHEN NOT MATCHED BY source and target.A1_ID= source.A2_ID
THEN DELETE
END
答案 1 :(得分:1)
我将向您展示一种在SQL Server 2000或2005中进行检查的简单方法,但总的来说,我同意Remus的观点,即您应该将它们分解为单独的触发器:
DECLARE @insert INT, @delete INT;
SELECT @insert = COUNT(*) FROM inserted;
SELECT @delete = COUNT(*) FROM deleted;
IF @insert +@delete > 0
BEGIN
IF @insert > 0 AND @delete = 0
-- insert
IF @insert > 0 AND @delete > 0
-- update
IF @insert = 0 AND @delete > 0
-- delete
END
请注意,由于MERGE在SQL Server 2008/2012中引入的复杂性,这可能无法完全向前兼容。
因此,如果您计划将来使用SQL Server 2008/2012和MERGE,就像上面的解决方案一样,那么这就更有理由将触发器拆分为每种类型的DML操作的触发器。