sqlserver两张表数据同步方法(触发器)
在开发的时候,会遇到当操作一张表的数据时,也想在另一张表中操作数据。这时我们就可以使用触发器来实现。
例如在用户表sys_user中插入和删除数据的时候,也ACT_ID_USER表做插入和删除的操作。
CREATE
TRIGGER
[dbo].[userTrigger]
-- dbo数据拥护者,userTrigger触发器名字
ON
[dbo].[sys_user]
-- 代表监听sys_user这个表
AFTER
INSERT
,
DELETE
-- 只有插入和删除可以触发这个监听器
AS
BEGIN
DECLARE
@IsInsert
bit
,
@IsDelete
bit
IF EXISTS(
SELECT
1
FROM
inserted)
AND
NOT
EXISTS(
SELECT
1
FROM
deleted)
-- inserted指新增的记录
SET
@IsInsert = 1
ELSE
SET
@IsInsert = 0
IF
NOT
EXISTS(
SELECT
1
FROM
inserted)
AND
EXISTS(
SELECT
1
FROM
deleted)
SET
@IsDelete = 1
ELSE
SET
@IsDelete = 0
if (@IsDelete=1)
delete
from
ACT_ID_USER
where
ID_
in
(
select
deleted.user_id
from
deleted)
if (@IsInsert=1)
insert
into
ACT_ID_USER(ID_)
select
inserted.user_id
from
inserted
END
GO
本文地址:http://yayihouse.com/yayishuwu/chapter/1042