SQL第五章习题

use [Stu1]

create table people (
num char(9) primary key ,
pname char(9) ,
age smallint check(age<=60),
pmoney smallint,
position char(9),
jobnum char (9),

)

create table 部门(
jobnum char(9) ,
名称 char(9),
经理名 char(9),
电话 char(9),
constraint constraint_jobnum primary key (jobnum)
)

alter table 部门 add constraint from_people_jobnum foreign key(jobnum) references  on people(jobnum )  on update cascade 

第二题
(1)

 create table score (
   学科 char(9),
   分数段 char(9),

   人数 smallint ,
   primary  key (学科,分数段)
   )


if exists(select * from sys.objects where name='pro_tran')
 drop procedure pro_tran
--不能一起用
 create procedure pro_tran 
 as 
 begin transaction trans
 declare 
 @num60 smallint,
 @num60_80 smallint,
 @num80_100 smallint ;
 
 select @num60=count(*) from SC where Grade <60 and Cno ='离散'

 select @num60_80=count(*) from SC where Grade <80 and Grade >60 and Cno ='离散'
 select @num80_100=count(*) from SC where Grade <100 and Grade>80 and   Cno ='离散'

 begin 

 insert into score values('离散','60-80',@num60_80)
 insert into score values('离散','80-100',@num80_100)
commit transaction trans --这一句和begin对应
return 
--记得结束
 end

测试

exec pro_tran
select *from score 

在这里插入图片描述
(2)任意的平均成绩



 create table avgscore(
 学科 char(9) primary key, 
 成绩 smallint ,

 )

if exists(select * from sys.objects where name='pro_tran')
drop procedure pro_tran

create procedure pro_tran
@cno char(9)
as 
begin transaction trans
declare 
@num  smallint;
select @num=avg(Grade)
from SC 
where Cno =@cno
insert into avgscore values(@cno,@num)
commit transaction trans 
return ;

exec pro_tran 
@cno='离散'
select *from avgscore
exec pro_tran 
@cno='数学'
select *from avgscore

在这里插入图片描述

(3)

alter table SC add scoreposition char(2)

if exists(select * from sys.objects where name='pro_tran')
drop procedure pro_tran

create procedure pro_tran

as 
begin transaction trans
update SC set scoreposition ='a'
where Grade >=90 and Grade<=100
update SC set scoreposition ='b'
where Grade >=80 and Grade<90
update SC set scoreposition ='c'
where Grade >=70 and Grade<80
update SC set scoreposition ='d'
where Grade >=60 and Grade<70
update SC set scoreposition ='d'
where  Grade<60
commit transaction trans 
return ;

exec pro_tran 

select *from SC




在这里插入图片描述

总结
存储过程的创建结构:
create procedure <名称>
<定义变量>–类似函数形参
–begin transaction <名称>
declare --局部变量
begin
<代码体>
commit transaction <名称>
|- - return ;
end
注意条件在存储过程中的重要性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值