我有A表,B表。我希望能用触发器来更新B表。
当A表添加一条记录,B表同时根据A表的a字段删除该记录,并且插入最新的记录。
A表
sno xm
0001 王平B表
sno xm
0001 杨佳
0002 王斌
0003 何亮现在在A表中插入(0002 杨建)得到
A表
sno xm
0001 王平
0002 杨建 B表
sno xm
0001 杨佳
0002 杨建
0003 何亮 请各位大侠指点
当A表添加一条记录,B表同时根据A表的a字段删除该记录,并且插入最新的记录。
A表
sno xm
0001 王平B表
sno xm
0001 杨佳
0002 王斌
0003 何亮现在在A表中插入(0002 杨建)得到
A表
sno xm
0001 王平
0002 杨建 B表
sno xm
0001 杨佳
0002 杨建
0003 何亮 请各位大侠指点
on A
after insert
as
if exists(select * from inserted i
join B on i.sno=b.sno)
update b
set b.xm=i.xm
from inserted i
join b
on i.sno=b.sno
else
insert into b(sno,xm)
select sno,xm
from inserted i
go
as
set nocount on
delete a from B表 a join DELETED d on a.sno=b.sno
insert B表 select * from INSERTED
set nocount off
create table table1 (sno varchar(10),xm varchar(10))
create table table2 (sno varchar(10),xm varchar(10))/**********插入记录************/insert into table1
select '0001','王平'
insert into table2
select '0001','杨佳' union all
select '0002','王斌' union all
select '0003','何亮' select * from table1
select * from table2
/*
table1
sno xm
---------------
0001 王平table2
sno xm
--------------
0001 杨佳
0002 王斌
0003 何亮
*/gocreate trigger t_table1 on table1
after delete,insert,update
as
begin
delete from table2 where sno in (select sno from deleted) if not exists (select 1 from table2 a,inserted i where a.sno=i.sno)
insert into table2
select * from inserted
else
update a set a.xm=i.xm from table2 a,inserted i where a.sno=i.sno
endgo
insert into table1
select '0002','杨建'select * from table1
select * from table2
/*
table1
sno xm
--------------
0001 王平
0002 杨建table2
sno xm
--------------
0001 杨佳
0002 杨建
0003 何亮
/*/********删除测试**********/drop table table1,table2
我是菜鸟,请问上面这句的意思是什么?
create table A表(sno varchar(20),xm varchar(20))
insert into A表 select '0001','王平'create table B表(sno varchar(20),xm varchar(20))
insert into b表 select '0001','杨佳'
insert into b表 select '0002','王斌'
insert into b表 select '0003','何亮'--触发器 A表
drop trigger xxx
Create trigger xxx
on A表
for insert
as
Begin
delete from b表 where sno in(select sno from inserted)
insert into b表 select * from inserted
Endinsert into A表 select '0002','杨建'
inserted表是一个逻辑表,它包含了已经插入的数据行的一个副本。我也是菜鸟,希望我的解释对你有帮助!