想问一问这个触发器如何写

fstao 2006-01-18 09:32:33
比如表t1,数据如下:
id f1
1 10
2 30
3 40



表t2的数据如下(id_t1关联t1.id):
id id_t1 f2
1 2 10
2 3 15


如果修改t2.id=1时,把t2.f1=10更新(update)之前,根据t2.id_t1=2,找到t1.id=2,使得t1.f1=t1.f1-t2.f2=30-10=20,使表t1变为:
id f1
1 10
2 20
3 40


如果修改t2.id=2时,把t2.f1=15更新(update)之前,根据t2.id_t1=3,找到t1.id=3,使得t1.f1=t1.f1-t2.f2=40-15=25,使表t1变为:
id f1
1 10
2 20
3 25


请问这个触发器如何实现?
...全文
146 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
$扫地僧$ 2006-01-18
  • 打赏
  • 举报
回复
改动一下;
CREATE TRIGGER TEMP_SC ON T2
INSTEAD OF update
as
update T1 set f1=f1-T2.f2 from T1,T2,inserted where inserted.id=T2.id and T2.id_t1=T1.id
update T2 set f2=inserted.f2 from T2,inserted where inserted.id=T2.id
$扫地僧$ 2006-01-18
  • 打赏
  • 举报
回复
Try:
create table T1
(
id int,
f1 int
)

create table t2
(
id int ,
id_t1 int,
f2 int
)

insert t1 select 1,20
insert t1 select 2,30
insert t1 select 3,40

insert t2 select 1,2,10
insert t2 select 2,3,15


CREATE TRIGGER TEMP_SC ON T2
INSTEAD OF update
as
update T1 set f1=f1-T2.f2 from T1,T2,inserted where inserted.id=T2.id and T2.id_t1=T1.id
samfeng_2003 2006-01-18
  • 打赏
  • 举报
回复
create table t1
(id int,f1 int)

create table t2
(id int,id_t1 int,f2 int)

insert t1
select 1,10 union all
select 2,30 union all
select 3,40

insert t2
select 1,2,10 union all
select 2,3,15
go
create trigger t_t2
on t2
for update
as
set xact_abort on
begin tran
update t1 set f1=b.f1-a.f2
from deleted a,t1 b where a.id_t1=b.id
commit tran
go

select * from t1

update t2 set id_t1=1
where id_t1=2

select * from t1

update t2 set id_t1=3
where id_t1=3

select * from t1


drop table t1,t2

(所影响的行数为 3 行)


(所影响的行数为 2 行)

id f1
----------- -----------
1 10
2 30
3 40

(所影响的行数为 3 行)


(所影响的行数为 1 行)


(所影响的行数为 1 行)

id f1
----------- -----------
1 10
2 20
3 40

(所影响的行数为 3 行)


(所影响的行数为 1 行)


(所影响的行数为 1 行)

id f1
----------- -----------
1 10
2 20
3 25

(所影响的行数为 3 行)

34,838

社区成员

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

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