]--试试
create table a(id int,档案编号 varchar(20),人数 int)
insert a select 1, '10001', 2
union all select 2, '10002', 4
union all select 3, '10005', 3
create table b(id int,档案编号 varchar(20), 成员编号 varchar(20))
insert b select 1, '10001', '10001-001'
union all select 2, '10001', '10001-002'
union all select 3, '10002', '10002-001'
union all select 4, '10002', '10002-002'
union all select 5, '10002', '10002-003'
union all select 6, '10002', '10002-004'
union all select 7, '10005', '10005-001'
union all select 8, '10005', '10005-002'
union all select 9, '10005', '10005-003'
sp_configure 'nested triggers',0
create trigger triaa on a
for update
as
if update(档案编号)
begin
update b set b.档案编号=c.档案编号,成员编号=replace(成员编号,b.档案编号,c.档案编号) from deleted a,inserted c where a.id=c.id and a.档案编号=b.档案编号
update a set 人数=(select count(1) from b where b.档案编号=a.档案编号)
end
go
create trigger triab on a
for delete
as
delete from b where 档案编号 in(select 档案编号 from deleted)
go
create trigger triba on b
for update
as
if update(档案编号)
begin
update b set b.成员编号=replace(b.成员编号,a.档案编号,c.档案编号) from deleted a,inserted c where a.id=c.id and b.id=a.id
update a set 人数=(select count(1) from b where b.档案编号=a.档案编号)
end
go
create trigger tribb on b
for insert
as
if exists(select 1 from a,b where a.档案编号=b.档案编号)
update a set 人数