求高手写一个触发器。
有两张表Test1和Test2:
Test1
ffid ffno note
Test2
wwid wwno bak
现在要写两个触发器,一个是insert触发器,一个是delete触发器。
insert触发器的要求是,
Test1有任意一条记录或者多条记录插入时,自动把Test1的ffid写入Test2的wwid,以及把
Test1的ffno写入Test2的wwno,至于的Test2的bak字段的值不要动。
delete触发器的要求是,
Test1有任意一条记录或者多条记录删除时,自动把Test2的wwid等于Test1表的ffid的记录删除。
备注,现在Test1和Test2都在同一个库里面。今后可能不在同一个库里面,最好把不在同一个库里面
的情况的触发器也写一下。
谢谢大侠们!
[解决办法]
给你写了一个,你可以参考一下哈:
create table test1(ffid int,ffno varchar(20), note varchar(30))
create table Test2(wwid int,wwno varchar(20), bak varchar(30))
create trigger dbo.trigger_test1_insert
on test1
for insert
as
insert into Test2(wwid,wwno)
select ffid,ffno
from inserted
go
create trigger dbo.trigger_test1_delete
on test1
for delete
as
delete Test2
from deleted d
where d.ffid = Test2.wwid
go
--1.插入
insert into test1
values(1,'aaa','xxx')
--数据也插入到了test2
select *
from Test2
/*
wwidwwnobak
1 aaa NULL
*/
--2.删除
delete from test1 where ffid = 1
--发现已经被删掉了
select *
from Test2
/*
wwidwwnobak
*/
use db1
go
if exists(select 1 from sys.triggers where name ='tr_test')
drop trigger tr_test
go
create trigger tr_test
on tb1
for insert,delete
as
if exists(select 1 from inserted) and not exists(select 1 from deleted)--插入操作
begin
insert db2..tb2
select .... from db1..tb1
end
if exists(select 1 from deleted) and not exists(select 1 from inserted)--如果删除操作
begin
delete from db2..tb2 where exists(select 1 from db1..tb1 where ....)
end