触发器作业参考答案

触发器作业1参考答案
在gongcheng数据库中,用触发器实现约束:如果是北京的供应商,供应任何零件的数量不能少于300,如果少于则自动改为300。
****************************************************************************************************************
方法一:
CREATE TRIGGER t1 ON [dbo].[SPJ]
FOR INSERT,UPDATE
AS
declare @sno char(4),@pno char(4),@jno char(4),@city char(20), @qty int
select @city=city , @sno=inserted.sno, @pno=pno,@jno=jno,@qty=qty
from inserted,S
where inserted.sno=s.sno
if @city='北京' and @qty<300
update SPJ
set qty=300
where sno=@sno and pno=@pno and jno=@jno

方法二:
update spj
set qty=300
from inserted,spj
where inserted.sno in (select sno from s where city='北京')
and inserted.sno=spj.sno and inserted.pno=spj.pno and inserted.jno=spj.jno and inserted.qty<300

--测试数据
--单行插入与更新
insert into spj
values('S2','P1','J2',100);

insert into spj
values('S1','P1','J2',100);

update spj
set qty=200
where sno='S2'and pno='p5' and jno='J1';

方法三:
CREATE TRIGGER t2 ON [dbo].[SPJ]
FOR INSERT,UPDATE
AS
declare record cursor for select * from inserted --建立游标
open record --打开游标
fetch next from record --推进游标
while @@FETCH_STATUS=0
begin
update spj
set qty=300
from inserted,spj
where inserted.sno in (select sno from s where city='北京')
and inserted.sno=spj.sno and inserted.pno=spj.pno and inserted.jno=spj.jno and inserted.qty<300
fetch next from record
end
close record --关闭游标

--测试数据
--多行更新
update spj
set qty=200
where sno='S2'and pno='p3';



触发器作业2参考答案:
(1)在学生选课数据库的SC关系中增加属性列Status,用来记录课程成绩的等级,0-59分为“不合格”,60-69为“合格”,70-89为“良好”,90以上为“优秀”。
(2)要求status属性列的值由用户在插入、更新选课成绩时系统自动填写和更新。
***********************************************************************************************************************************************
alter table sc add status char(10);

CREATE TRIGGER t1_sc ON [dbo].[SC]
FOR INSERT,UPDATE
AS
declare @sno char(8),@cno char(10),@grade int,@status char(10)
select @sno=sno,@cno=cno,@grade=grade from inserted
select @status=
case
when @grade < 60 then '不合格'
when @grade >=60 and @grade<70 then '合格'
when @grade >=70 and @grade<90 then '良好'
else '优秀'
end
update sc set status=@status where sno=@sno and cno=@cno and grade=@grade

--测试数据
insert into sc
values('09105102','003',92,null)

update sc
set grade=77
wh

ere sno='09105102' and cno='003'

相关文档
最新文档