表明MS SQL SERVER 会将游标定义所选取出来的数据记录存放在一临时表内(建立在tempdb 数据库下)。对该游标的读取操作皆由临时表来应答。因此,对基本表的修改并不影响游标提取的数据,即游标不会随着基本表内容的改变而改变,同时也无法通过游标来更新基本表。如果不使用该保留字,那么对基本表的更新、删除都会反映到游标中。
游标指针示意图

详细:
1.定义一个标准游标:
declare
mycursor
cursor
for
select
*
from
yuangong
2.定义一个只读游标:
declare
mycursor
cursor
for
select
*
from
yuangong
for
read
only
3.定义一个可写游标:
declare
mycursor1
cursor
for
select
*
from
yuangong
for
update
of
姓名,性别,年龄,基本工资,奖金,所得税,应发工资
注: scroll 只能对只读游标起作用
4.打开游标:open 游标名
如:
declare
mycursor
cursor
for
select
*
from
yuangong
open
mycursor
5.从游标中取数据:fetch,默认情况下,指针指向第一条记录之前
移动记录指针的方法:
NEXT 下移一条记录
prior 上移一条记录
first 第一条记录
LAST 最后一条记录
absolute n 绝对记录 第N条记录
取数据语法:
fetch
next
|
prior
|
first
|
last
|
absolute n
6.关闭游标: close 游标名
暂时关闭游标,还可再使用OPEN打开.
7.释放游标: deallocate 游标名
从内存中清除游标.如果还想使用,必须再次声明.
对当前游标状态进行判断:
8. @@fetch_status 如果返回是0,说明当前操作是成功的.否则是失败的.
0 FETCH 语句成功。
-1 FETCH 语句失败或此行不在结果集中。
-2 被提取的行不存在。
(三)实例代码
举例1:
利用游标从学生表中逐条读取所有数据:
declare
@i
INT
DECLARE
@TN
CHAR
(
8
),
@FU
CHAR
(
20
)
declare
mycursor
cursor
for
select
sno,sname
from
student
open
mycursor
select
@i
=
count
(
*
)
from
student
while
@@fetch_status
=
0
and
@i
>
1
BEGIN
fetch
next
from
mycursor
INTO
@TN
,
@FU
set
@i
=
@i
-
1
PRINT
@TN
+
'
'
+
@FU
END
close
mycursor
deallocate
mycursor
结果:
s1001 Jack Dong
s1002 Lucy Dong
s1003 Brezse Dong
举例2:
通过游标对读取的数据进行操作,并输出不同的结果:
declare
@s_name
varchar
(
20
),
@c_name
VARCHAR
(
64
),
@sc_core
int
declare
my_cur
cursor
for
select
sname,cname,scgrade
from
student s, course c, studentCourse sc
WHERE
s.sno
=
sc.sno
AND
c.cno
=
sc.cno
open
my_cur
print
space
(
27
)
+
'
2007年计算机专业考试系统
'
fetch
next
from
my_cur
into
@s_name
,
@c_name
,
@sc_core
while
@@fetch_status
=
0
begin
if
@sc_core
<</SPAN>60
begin
print space(20)+@s_name+ @c_name +':不及格 '
end
else
begin
if @sc_core >=60 and @sc_core <</SPAN>70
begin
print space(20)+@s_name + @c_name +':及格 '
end
else
begin
if @sc_core>=70 and @sc_core<</SPAN>80
begin
print space(20)+@s_name + @c_name +':良好'
end
else
begin
print space(20)+@s_name + @c_name +':优秀'
end
end
end
fetch next from my_cur into @s_name,@c_name,@sc_core
end
close my_cur
deallocate my_cur
结果:
2007年计算机专业考试系统
Jack Dong C++ 程序设计:及格
Jack Dong 操作系统:良好
Lucy Dong C++ 程序设计:优秀
Lucy Dong 计算机组成原理:良好
Brezse Dong C++ 程序设计:优秀
Brezse Dong 面向对象的程序设计方法:不及格
Andy Liu 操作系统:不及格
Andy Liu 计算机组成原理:优秀
使用游标时应注意的问题:
(1) 尽管使用游标比较灵活,可以实现对数据集中单行数据的直接操作,但游标会在下面几个方面影响系统的性能:
-使用游标会导致页锁与表锁的增加
-导致网络通信量的增加
-增加了服务器处理相应指令的额外开销
(2) 使用游标时的优化问题:
-明确指出游标的用途:for read only或for update
-在for update后指定被修改的列