求一个简单的触发器

pgdoryoku 2008-01-19 03:26:56
平台:mssql2000
条件:1、已知有两表,表A和表B
2、表A中有字段,A1,A2
3、表B中有字段,B1,B2
问题:当更新表A中的A2字段的同时,更新表B中所有B2字段中的B2=A2的所有字段为新的A2。
要求:要有该触发器要有容错功能,且在建立之前会判断是否有同名触发器存在,有的话则删除同名的触发器在建立触发器。
...全文
73 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
sun9moon 2008-01-20
  • 打赏
  • 举报
回复
create table a(a1 int,a2 int)
insert into a select 1,1
insert into a select 2,2

create table b(b1 char(1),b2 int)
insert into b select 'a',1
insert into b select 'b',1
insert into b select 'c',2
insert into b select 'd',2
insert into b select 'e',2
go
if exists(select 1 from sysobjects where name ='ut_a_update' and type='tr')
drop trigger ut_a_update
go
create trigger ut_a_update on a for update
as
update b set b2=i.a2
from inserted i join deleted d on i.a1=d.A1
join b on b.b2=d.a2
go
--测试
select * from b
update a set a2=3 where a2=1
select * from b

drop table a
drop table b
go
中国风 2008-01-19
  • 打赏
  • 举报
回复
inserted i join deleted d on i.A1=D.A1
这句什么意思?

inserted --别名为i表
deleted --别名为d表
中国风 2008-01-19
  • 打赏
  • 举报
回复
deleted 和 inserted 是逻辑(概念)表

--一个是更新前,一个是更新后状态
pgdoryoku 2008-01-19
  • 打赏
  • 举报
回复
谢谢,在问下2楼的语句中
inserted i join deleted d on i.A1=D.A1
这句什么意思?
wzy_love_sly 2008-01-19
  • 打赏
  • 举报
回复
create table a(a1 int,a2 int)
insert into a select 1,1
insert into a select 2,2


create table b(b1 int,b2 int)
insert into b select 1,1
insert into b select 2,1
insert into b select 3,2
insert into b select 4,2
insert into b select 5,2

create trigger tr_a
on a
for update
as
begin
update a set b2=b.a2 from b a,deleted c,inserted b
where a.b2=c.a2 and c.a1=b.a1
end

update a set a2=5 where a1=1

select * from a

select * from b

--a
a1 a2
1 5
2 2
--b
b1 b2
1 5
2 5
3 2
4 2
5 2


中国风 2008-01-19
  • 打赏
  • 举报
回复
如果是唯一的情况下建级联更新A的A2上
中国风 2008-01-19
  • 打赏
  • 举报
回复
create trigger tr_A on A
for update
as
update B
set B2=i.A2
from
inserted i join deleted d on i.A1=D.A1
join B on B2=d.A2
dawugui 2008-01-19
  • 打赏
  • 举报
回复
create trigger my_trig on A for update
as
update b set b2 = a.a2 from b,a where b.b1 = a.a1

34,837

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧