分别创建增加、删除、更新的触发器(Trigger)来达到两张表之间数据同步的目的。
1:数据同步增加:
如有两张表——A表和B表,创建触发器使当A表插入数据后B表也同步插入数据。其中B表插入数据的字段需要同A表中的字段相对应。
CREATE TRIGGER 触发器名称
ON A表
AFTER INSERT
AS BEGIN INSERT INTO
B表(B表字段1,B表字段2,B表字段3)
SELECT A表字段1,A表字段2,A表字段3
FROM INSERTED
END
ON A表
AFTER INSERT
AS BEGIN INSERT INTO
B表(B表字段1,B表字段2,B表字段3)
SELECT A表字段1,A表字段2,A表字段3
FROM INSERTED
END
2.数据同步删除:
如有两张表——A表和B表,创建触发器使当A表删除数据后B表也同步删除数据。其中B表与A表应有相应主键关联。
CREATE TRIGGER 触发器名称
ON A表
AFTER DELETE
AS BEGIN DELETE B表
WHERE
B表主键 IN(
SELECT A表主键
FROM DELETED)
END
ON A表
AFTER DELETE
AS BEGIN DELETE B表
WHERE
B表主键 IN(
SELECT A表主键
FROM DELETED)
END
3.数据同步更新:
如有两张表——A表和B表,创建触发器使当A表数据更新后B表也同步更新数据。
CREATE TRIGGER 触发器名称
ON A表
AFTER UPDATE
AS
update B表
SET
B.B表字段1=A.A表字段1
FROM
B表 AS B,INSERTED AS A
WHERE B.B表主键=A.A表主键
ON A表
AFTER UPDATE
AS
update B表
SET
B.B表字段1=A.A表字段1
FROM
B表 AS B,INSERTED AS A
WHERE B.B表主键=A.A表主键