一个关于instead of 的问题

haoxiaa115 2007-12-15 06:09:25
目的是创建一个instead of触发器,使得插入和更改SC表中学生的成绩grade的时候,如果成绩在80分以上,学分值为相应C表中的值,如果低于,则学分值为0
程序如下:
create trigger ins_credit
on sc
instead of update,insert
as
begin
if(select grade from inserted)>80
begin
update sc
set getcredit=(select credit from course where cno in(select cno from inserted))
where sno in (select sno from inserted) and cno in (select cno from inserted)
end
else
begin
update sc
set getcredit=0
where sno in(select sno from inserted) and cno in (select cno from inserted)
end
end
现在小弟的问题是 instead of后面跟的如果是insert的话,数据就不能插入到SC表中去,因为被instead of掉了如:insert into SC values('20050003','002','81',NULL).
如果后面是update的话,虽然能起到学分的更新作用,但是SC表中的数据却不能相应更新.如:update sc
set grade=45
where sno='20050002'and cno='002'
这样学分值是更新为0了,但是因为instead of相应的sc中的grade却没有更新....
怎么样才能使数据一边能够达到更新插入的效果,一边学分更新功能能够实现.
但题目却指定要用instead of触发器 即达到学分更新效果又能让update 和insert操作执行.是不是instead of后面的操作就被直接替代掉了?

...全文
382 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
cxmcxm 2007-12-15
  • 打赏
  • 举报
回复
instead of 证明是替代触发器,也就是触发器的内容替代了你的输入的insert into 或update语句,
所以,要使能插入数据或更新数据,必须在触发器里加上插入与update语句,数据才能插入与更新
对插入触发,必须在触发器里加上
insert into 表名 select * from inserted
对更新触发,必须加上
update a
set 字段1=inserted.字段1,
字段2=inserted.字段2,
.....
from 表名,inserted where 定位到inserted记录的条件语句




haoxiaa115 2007-12-15
  • 打赏
  • 举报
回复
我后来自己弄出来了 在if(select grade from inserted)> 80 和ELSE后面分别加上在前面加个if(insert getcredit from inserted)!=NULL
begin
insert into sc select *from inserted
end
就二边都不冲突了 所有功能都没问题了..难道修改的时候getcredit在insert表里面是NULL?
中国风 2007-12-15
  • 打赏
  • 举报
回复
非要用instead of 时,举个例子:

sc表有ID和getcredit列
---ID就主健

create trigger ins_credit on sc
instead of update,insert

if not exists(select 1 from deleted)--操作为新增
begin
insert sc
select
ID,case when getcredit>80 then (select credit from course where cno=i.cno) else 0 end
from
inserted i
end
else --其它为更新
begin
update j
set grade=i.grade,getcredit=case when i.getcredit>80 then (select credit from course where cno=i.cno) else 0 end
from
inserted i join cs j on i.ID=j.ID
end
haoxiaa115 2007-12-15
  • 打赏
  • 举报
回复
但题目就是指定用instead of太郁闷了 这么说是题目有问题?
中国风 2007-12-15
  • 打赏
  • 举报
回复
INSTEAD OF

指定执行触发器而不是执行触发 SQL 语句,从而替代触发语句的操作。

----------
改为after /for 触发器

34,576

社区成员

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

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