日期:2014-05-18  浏览次数:20393 次

教教一个触发器的问题?无限感谢
表A有一个 是否字段(值为 是 或 否) ,我想如果把 是否字段 修改为 是或否 ,则触发表B 的 数量字段加1或减1。不知道这个sqlserver   2000是否支持?



------解决方案--------------------
create trigger auto_update on 表A
for update

update 表B set 数量字段 = 数量字段+(select sum(case when 是否字段 = '是 ' then 1 when 是否字段 = '否 ' then -1) from inserted)
------解决方案--------------------
表A有一个 是否字段(值为 是 或 否) ,我想如果把 是否字段 修改为 是或否 ,则触发表B 的 数量字段加1或减1。不知道这个sqlserver 2000是否支持?

create trigger tri_name on A
for update
as
if update(字段名)
begin
if (select count(*) from inserted where 字段名= '是 ')> 0
begin
update B set 数量字段=数量字段+1
end
if (select count(*) from inserted where 字段名= '否 ')> 0
begin
update B set 数量字段=数量字段-1
end
end

go

总觉得两表之间应该还有个字段作为连接条件,要不就全update
------解决方案--------------------
大概
create trigger tr_a_update
on a
for update
as

update b
set 数量=isnull(b.数量,0)+t.num
from b,(
select 关键字,sum(num) as num
from (
select 关键字,case 是否 when '是 ' then 1 else 0 end as num from inserted
union all
select 关键字,case 是否 when '是 ' then -1 else 0 end as num from deleted
) as t1
group by 关键字
) as t
where b.关键字=t.关键字

go


------解决方案--------------------
create trigger auto_update on 表A
for update

update 表B set 数量字段 = 数量字段+(
select sum(case when 是否字段 = '是 ' then 1 when 是否字段 = '否 ' then -1 end) from inserted
)

------解决方案--------------------
create trigger tr_update on A
for update
as
declare @flag varchar(10)
select @flag=字段 from inserted
if @flag= '是 '
update b set 数量=数量+1
else
update b set 数量=数量-1
------解决方案--------------------
1楼,当没修改是否字段的时候加的数量不对
2楼,当一次修改多条记录的时候只加1或者减1


------解决方案--------------------
create trigger tr_学生选课_update
on 学生选课
for update,INSERTE,DELETE
as

update b
set 选课人数=isnull(b.选课人数,0)+t.num
from 课程 b,(
select 课程编号,sum(num) as num
from (
select 课程编号,case 是否通过 when '是 ' then 1 else 0 end as num from inserted
union all
select 课程编号,case 是否通过 when '是 ' then -1 else 0 end as num from deleted
) as t1
group by 课程编号
) as t
where b.课程编号=t.课程编号

go