数据库游标的设计

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验10:游标

【实训目的】

掌握游标的定义及使用

【实训步骤及内容】

1、游标包括以下两部分

1)结果集(Result set)

2)游标位置(Cursor position)

通过游标提供了对一个结果集进行逐行处理的能力

游标可以被看作一个表中的记录指针,该指针与某个查询结果相联系。

在某一时刻,该指针只指向一条记录,即游标是通过移动指向记录的指针来处理数据。

2、@@FETCH_STATUS的值及描述

3、游标使用的步骤

声明游标

DECLARE cursor_name CURSOR FOR select_statement

打开游标

OPEN cursor_name

取游标

FETCH next FROM cursor_name [INTO @variable_name]

关闭游标

CLOSE cursor_name

释放游标

DEALLOCATE cursor_name

1、使用游标分行显示课程表(course)中的信息

declare cur_course cursor for

select*from course

open cur_course

fetch next from cur_course

while@@fetch_status=0

begin

fetch next from cur_course--游标位置下移

end

close cur_course

deallocate cur_course

2、定义存储过程,输入学生学号返回学生选修课程的课程号,成绩。使用

output输出参数保存输出数据。(提示:使用游标输出参数)

create proc proc_01

@sid char(11),@cur_cid_score cursor varying output

as

set @cur_cid_score=cursor for

select c_id,score from stu_score

where s_id=@sid

open @cur_cid_score

go

--调用

DECLARE @MyCursor CURSOR

EXEC proc_01 '0702301102',@cur_cid_score = @MyCursor OUTPUT

FETCH NEXT FROM @MyCursor

WHILE(@@FETCH_STATUS= 0)

BEGIN

FETCH NEXT FROM @MyCursor

END

CLOSE @MyCursor

DEALLOCATE @MyCursor

3、创建触发器tri_stu_ifno,实现删除stu_info表中不同班级多条记录的同时,

更新班级表中的人数。(提示:嵌入游标)

create trigger tri_cursor

on stu_info

for delete

as

declare @classid char(8)

declare @cur_stu_info cursor

set @cur_stu_info=cursor for

select class_id from deleted

open @cur_stu_info

fetch next from @cur_stu_info into @classid

while@@fetch_status=0

begin

update class

set class_rs=class_rs-1

where class_id=@classid

fetch next from @cur_stu_info into @classid

end

close @cur_stu_info

deallocate @cur_stu_info

go

alter table stu_score

nocheck constraint fk_stu_score_stu_info

delete from stu_info

where s_id='0702301101'or s_id='0702301102'

alter table stu_score

with check check constraint fk_stu_score_stu_info 4、创建如下员工表:

利用游标按以下条件调整工资

①职称为助教增加300

②职称为讲师增加500

③职称为副教授增加800

④职称为教授增加1000

declare cur_salary cursor for

select title from employee_salary

declare @title char(10)

open cur_salary

fetch next from cur_salary into @title

while@@fetch_status=0

begin

if @title='助教'

begin

update employee_salary

set wage=wage+300

where current of cur_salary

end

else if @title='讲师'

begin

update employee_salary

set wage=wage+500

where current of cur_salary

end

else if @title='副教授'

begin

update employee_salary

set wage=wage+800

where current of cur_salary

end

else if @title='教授'

begin

update employee_salary

set wage=wage+1000

where current of cur_salary

end

fetch next from cur_salary into @title

end

if@@fetch_status=-1

begin

close cur_salary

deallocate cur_salary

end

5、使用游标显示如下生格式的学生选修课程情况。--- 梁宇新 ---

相关文档
最新文档