九.SQL server 事务、锁与游标问题

一.实验目的

1.了解游标的基本作用,了解游标的种类;

 2.了解使用游标的方法,掌握使用游标的基本步骤;

 3. 掌握事务和锁的操作技巧。

二.实验内容

1.声明一个游标,用于查询所有计算机专业的学生的学号、籍贯、和年龄;

 2.创建一个事务l

 3.实现一个锁

三.实验步骤:

1. 声明一个游标,用于查询所有计算机系学生的学号和年龄,将声明游标、打开游标、使用游标、关闭游标的代码全部粘贴于下方:

<span style="font-size:18px;">Use 学生课程数据库
go
declare course_cur1 cursor
for select sno,sage from student
where sdept='计算机科学'
for read only
go
open course_cur1
fetch next from course_cur1
while @@FETCH_STATUS=0
begin
fetch next from course_cur1
end
close course_cur1
deallocate course_cur1</span>
2.声明一个游标,用于查询选课表(sc表)中课程为'1001'的全部信息,按分数降序排序;将声明游标、打开游标、使用游标、关闭游标的代码全部粘贴于下方;

<span style="font-size:18px;">Use 学生课程数据库
go
declare course_cur1 cursor
for select * from sc
where cno='1001'
for read only
go
open course_cur1
fetch next from course_cur1
while @@FETCH_STATUS=0
begin
fetch next from course_cur1
end
close course_cur1
deallocate course_cur1
 </span>

3.显示student表中的学生人数,开始一个事务,插入一条学生记录,再显示student表中的学生人数,如果学生总人数超过最大值(你自己根据测试数据来设定,如190),回滚该事务,并显示出错信息(如学生总数已满)。

<span style="font-size:18px;">DECLARE @renshu int
Select @renshu=count(*) from student
Print @renshu
BEGIN TRANSACTION
Insert into student(sno,sname,ty) values('2008056129','张丽领','true')
Select @renshu=count(*) from student
IF @renshu>130 --如果有错误
BEGIN
print'学生总数已满'
ROLLBACK TRANSACTION
END
ELSE
BEGIN
Print '插入成功,提交事务,写入硬盘,永久的保存'
COMMIT TRANSACTION
END</span>


4. 利用游标的方式实现:显示1001课程分数最高的学生所在的系别。

<span style="font-size:18px;">Use 学生课程数据库
go
declare course_cur1 cursor
for select sdept from sc, student	where grade in (select grade from sc where cno='1001')
for read only
go
open course_cur1
fetch next from course_cur1
while @@FETCH_STATUS=0
begin
fetch next from course_cur1
end
close course_cur1
deallocate course_cur1</span>


5. 定义一个游标Cursor_Famale。要求该游标返回所有女同学的基本信息,在游标中查找并显示刘晨男的记录。

<span style="font-size:18px;">Use 学生课程数据库
go
declare course_cur1 cursor
for select * from student
where ssex='女'
for read only
go
open course_cur1
fetch next from course_cur1
while @@FETCH_STATUS=0
begin
fetch next from course_cur1
end
close course_cur1
deallocate course_cur1
 
--查找刘晨
Use 学生课程数据库
go
declare course_cur1 cursor
for select * from student
where ssex='女' and sname='刘晨'
for read only
go
open course_cur1
fetch next from course_cur1
while @@FETCH_STATUS=0
begin
fetch next from course_cur1
end
close course_cur1
deallocate course_cur1
 </span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值