首页 新闻 赞助 找找看

sql 触发器问题

0
悬赏园豆:5 [已解决问题] 解决于 2010-03-17 16:41

A表结构

id    state

1     0

2     0

3     1

B表结构

id   state

1     1

1     1

1      0

2      0

2      0

3      1

3      1

A表的id 与B表的id 关联  当B表中的state 都等于1是  就对应更新A表中state(1)

like%'远远'%的主页 like%'远远'% | 小虾三级 | 园豆:635
提问于:2010-03-17 13:32
< >
分享
最佳答案
0

呵呵,这是一个简单的关联表的批量更新。举例如下:

use testdb
go

if OBJECT_ID('AAA') is not null
drop table AAA
go

if OBJECT_ID('BB') is not null
drop table BB
go

Create table AAA
(id
int
,
[state] int
)
go

Create table BB
(id
int
,
[state] int
)
go

insert into AAA
select 1,0
union all select 2,0
union all select 3,1

insert into BB
select 1,1
union all select 1,1
union all select 1,0
union all select 2,0
union all select 2,0
union all select 3,1
union all select 3,1

select * from AAA

Create trigger tri_UpdateBBToAAAWithByID on [dbo].BB
FOR INSERT,UPDATE
AS
Update AAA set [state]=p.[State]
from BB p inner join AAA q On p.id=q.id and p.[State]=1
and q.id in (select id from INSERTED)

go


select * from AAA
--id state
--
1 0
--
2 0
--
3 1

update BB set [State]=1 where id=1

select * from AAA

--id state
--
1 1
--
2 0
--
3 1

 

收获园豆:5
邀月 | 高人七级 |园豆:25475 | 2010-03-17 16:13
其他回答(1)
0

在对B表的数据进行修改或插入的时候,执行触发器,检查B表中的state 都等于1,如果都等于1 就对应更新A表中state(1)

风影极光 | 园豆:1573 (小虾三级) | 2010-03-17 15:37
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册