日期:2014-05-19  浏览次数:20372 次

求一触发器。请大家多帮忙!!!!!
我数据库中有4个表,表A、表B为数据表。表C用来记录A表中数据的变化,表D用来记录表B中的变化。
表结构:
A:id,单位名称,地址
B:id,单位id,车牌号
c:   id,单位id,单位名称
D:id,车牌号,车辆id
具体实现功能:
表A和表B中的数据只要发生变化时通过触发器,在表C和表D中存储相应的ID。
如果实施的是DELETE,那么就记录单位名称和车牌号。实施UPDATA和INSTER的时候只记录单位ID和车辆ID。插入记录的同时判断,如果表C和表D中已经存在相应的单位ID和车辆ID的时候不增加记录,如果已经存在记录,但现在实施的是删除操作,那么刷新那条记录的单位名称或是车牌号。

------解决方案--------------------
LCAAA(风) ( ) 信誉:100 Blog 2007-03-19 14:42:24 得分: 0


顺便问一下,怎么判断实施的操作是DEL还是INSTRER或是UPDATA呀


--------------
Inserted為空,Deleted不為空 --Delete
Inserted不為空,Deleted為空 --Insert
Inserted不為空,Deleted不為空 --Update

------解决方案--------------------
insert 操作:inserted 中有记录,deleted 中无记录
update 操作:inserted 中有记录,deleted 中有记录
delete 操作:inserted 中无记录,deleted 中有记录
------解决方案--------------------
这是A表的触发器
应该不用删除触发器,如果update触发器维护正确的话,单位名称就会一致.
create trigger ti_a on 表A
for insert
as
if not exists(select 1 from 表c,inserted i where 表c.单位id=i.id)
begin
insert into 表c(单位id,单位名称)
select id,单位名称
from inserted
where id not in(select 单位id from 表c)
end

create trigger tu_a on 表A
for update
as
if update(单位名称) and exists(select 1 from inserted i,deleted d where i.id=d.id and isnull(i.单位名称, ' ') <> isnull(d.单位名称, ' '))
begin
update 表c
set 单位名称=i.单位名称
from 表c,inserted i,deleted i
where 表c.单位id=i.id and i.id=d.id and isnull(i.单位名称, ' ') <> isnull(d.单位名称, ' ')
end