游标的使用分为两部分,一部分是操作游标在数据集内的指向,另一部分是将游标所指向的行的部分或全部内容进行操作。
支持6种移动导航,分别为:
第一行(FIRST)
最后一行(LAST)
下一行(NEXT)
上一行(PRIOR)
直接跳到某行(ABSOLUTE(n))
相对于目前跳几行(RELATIVE(n))
例如:
declare test_Cursor cursor scroll for
select name from Person;
open test_Cursor;
declare @c nvarchar(10);
--取下一行
fetch next from test_Cursor into @c;
print @c;
--取最后一行
fetch last from test_Cursor into @c;
print @c;
--取第一行
fetch first from test_Cursor into @c;
print @c;
--取上一行
fetch prior from test_Cursor into @c;
print @c;
--取第三行
fetch absolute 3 from test_Cursor into @c;
print @c;
--取相对目前来说上一行
fetch relative -1 from test_Cursor into @c;
print @c;
对于未指定SCROLL选项的游标来说(未指定,则是只进游标),只支持NEXT取值。
游标经常会和全局变量@@FETCH_STATUS与WHILE循环来共同使用,以达到遍历游标所在数据集的目的。
当执行一条Fetch语句之后,@@Fetch_Status可能出现3种值:
0,Fetch语句成功。
-1:Fetch语句失败或行不在结果集中。
-2:提取的行不存在。
游标总记录数 @@CURSOR_ROWS
例如:
declare test_Cursor cursor fast_forward for
select id, name from Person;
open test_Cursor;
declare @id int;
declare @name nvarchar(10);
fetch next from test_Cursor into @id, @name;
while @@FETCH_STATUS = 0
begin
print @id;
print @name;
fetch next from test_Cursor into @id, @name;
end;
close test_Cursor;
deallocate test_Cursor;
利用游标更新删除数据
游标修改当前行数据语法:
Update 基表名 Set 列名=值[,...] Where Current of 游标名
游标删除当前数行据语法:
Delete 基表名 Where Current of 游标名
举例:
---1.声明游标
declare orderNum_03_cursor cursor scroll for
select OrderId, userId from bigorder where orderNum = 'ZEORD003402';
--2.打开游标
open orderNum_03_cursor;
--3.声明游标提取数据所要存放的变量
declare @OrderId int, @userId varchar(15);
--4.定位游标到哪一行
fetch first from orderNum_03_cursor into @OrderId, @userId; -- into的变量数量必须与游标查询结果集的列数相同
while @@fetch_status = 0 --提取成功,进行下一条数据的提取操作
begin
if @OrderId = 122182
begin
update bigorder set UserId = '123' where current of orderNum_03_cursor; --修改当前行
end;
if @OrderId = 154074
begin
delete bigorder where current of orderNum_03_cursor; --删除当前行
end;
fetch next from orderNum_03_cursor
into @OrderId, @userId; --移动游标
end;
close orderNum_03_cursor;
deallocate orderNum_03_cursor;
关闭游标
在游标使用完之后,一定要记得关闭,只需要一行代码:CLOSE+游标名称
close test_Cursor
释放游标
当游标不再需要被使用后,释放游标,只需要一行代码:DEALLOCATE+游标名称
deallocate test_Cursor
对于游标一些优化建议
如果能不用游标,尽量不要使用游标
用完之后一定要关闭和释放
尽量不要在大量数据上定义游标
尽量不要使用游标上更新数据
尽量不要使用insensitive, static和keyset这些参数定义游标
如果可以,尽量使用FAST_FORWARD关键字定义游标
如果只对数据进行读取,当读取时只用到FETCH NEXT选项,则最好使用FORWARD_ONLY参数
这篇关于“SQL Server游标具体如何使用”的文章就介绍到这了,更多相关的内容,小编将为大家输出更多高质量的实用文章!