• 主页
• 基础类
• 应用实例
• 新技术前沿

# 求一个简单的触发器

pgdoryoku 2008-01-19 03:26:56

2、表A中有字段，A1，A2
3、表B中有字段，B1，B2

...全文
42 点赞 收藏 8

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

inserted i join deleted d on i.A1=D.A1

inserted --别名为i表
deleted --别名为d表

deleted 和 inserted 是逻辑（概念）表

--一个是更新前，一个是更新后状态

pgdoryoku 2008-01-19

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``````

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``````

MS-SQL Server

3.2w+

MS-SQL Server相关内容讨论专区