如何创建插入和更新的触发器,它将自动将数据从一个(源)表传输到另一个(destionation)表(不同数据库中的表)? 触发器需要在源表中的每次更改后传输数据。有谁知道怎么做?
答案 0 :(得分:1)
尝试这样的事情:
USE DB1;
GO
CREATE TRIGGER dbo.table1__AIU
ON dbo.table1
AFTER INSERT, UPDATE
AS BEGIN
SET NOCOUNT ON;
DECLARE @operation char(1) = -- [I]nsert, [U]pdate, u[N]known
CASE
WHEN EXISTS(SELECT * FROM inserted) THEN
CASE WHEN EXISTS(SELECT * FROM deleted) THEN 'U' ELSE 'I' END
ELSE 'N'
END;
IF @operation = 'N'
RETURN;
IF @operation = 'I'
INSERT INTO DB2.dbo.Table2(id, b)
SELECT inserted.id, inserted.b
FROM inserted;
ELSE
UPDATE t2
SET b = inserted.b
FROM DB2.dbo.Table2 t2
INNER JOIN inserted i ON t2.id = inserted.id;
END;
GO