日期:2014-05-18  浏览次数:20652 次

急!!!关于一个触发器问题
我在一个往表A中添加,删除,修改 数据也同时向表B中同步添加,删除,修改,不同的是表B是修改子节点位置的数据,它的上一节数据不变.不会添加最高节点的数据,只会添加子节点数据.请大家帮个忙.分不够再给

code       name
101         a
101001   b
101002   c
102002001   h

表B:

code       name
101         a
101001   a_b
101002   a_c
102002001   a_c_h

------解决方案--------------------
--当a表新增时触发
create trigger ainsert on a
for insert
as
begin
insert into b select * from inserted
end
--当a表删除时触发
create trigger ainsert on a
for delete
as
begin
delete from b from b,deleted d
where b.id=d.id
end
------解决方案--------------------
--------
/*
昨天说的话还没兑现.呵呵...
我写了个.针对是情况是:增加节点的时候,先增加父项;删除,则先删除子项.
不知道条件对不对了...
*/

create trigger t_a on a
for insert ,update ,delete
as
if not exists(select 1 from deleted )
begin
if not exists (select 1 from a join inserted i on left(a.code,len(i.code)) = i.code )
and not exists(select 1 from inserted i join a on left(i.code,len(a.code)) = a.code )
begin --考虑父项插入a表的情况
insert into b
select * from a
end
if exists(select 1 from inserted i join a on left(i.code,len(a.code)) = a.code )
begin --考虑子项的情况
insert into b
select i.code,a.name + '_ '+i.name from inserted i join a on left(i.code,len(a.code)) = a.code
end
end
if exists(select 1 from deleted d join inserted i on d.code =i.code)
begin
if not exists(select 1 from inserted i join a on left(a.code,len(i.code)) = i.code)
begin --考虑不是父项的更新
update t set name =b.name + '_ ' + i.name
from b t
join inserted i on t.code =i.code
join b m on left(t.code,len(b.code)) = b.code
end
end
if not exists(select 1 from inserted )
begin --好像这个是否子项这个条件不重要.
if not exists (select 1 from deleted d join a on left(a.code,len(d.code)) =d.code)
begin --考虑子项的删除
delete from b where exists (select 1 from deleted d where b.code =d.code )
end
else
begin --考虑不是子项的删除
delete from b where ( exists (select 1 from deleted d where b.code =d.code))
or (exists (select 1 from deleted d where left(b.code,len(d.code))=d.code))
end
end