Sqlserver游标复习

时间:2022-01-20 15:16:08

经常写存储过程,但今天在游标使用过程中还是疏忽了一些事情,执行过程中一直执行不下去,后来直接sqlserver挂了,教训啊!

代码虽简单,望铭记:

Create  PROCEDURE [dbo].[temphxb]
AS
BEGIN
declare @uid int
declare mycursortemp Cursor
for select uid from temptable1 where Indate>'2015-05-21' and type='' group by uid having COUNT(*)>
open mycursortemp
fetch next from mycursortemp into @uid while @@FETCH_STATUS=
begin
delete from temptable1 where id
in (select top id from temptable1 where uid=@uid and Indate>'2015-05-21' and fdtype='') update temptable2 set num=num+ where uid=@uid
fetch next from mycursortemp into @uid
end close mycursortemp
DEALLOCATE mycursortemp
end

游标使用过程中,一般分为以下五个步骤:
1、声明游标

2、打开游标

3、使用游标

4、关闭游标

5、删除游标

今天本人就是在第三步游标遍历数据中忘记去执行  fetch next from mycursortemp into @uid,导致死循环发生,造成不小的损失。
另外很多人忘记关闭游标,这也会造成下次执行发生错误。

数据库操作需要谨慎谨慎,切记。