sqlserver 使用游标过程中出现的错误

时间:2023-03-09 00:50:42
sqlserver 使用游标过程中出现的错误

下面的见解是在使用游标的过程中做的日记。我也是第一次使用,如果有什么不对的地方请批评指正,大家一起努力。

1.

  消息 16951,级别 16,状态 1,过程 usp_proc,第 16 行
      变量 '@myref' 不能用作参数,因为在执行该过程前,不得为 CURSOR OUTPUT 参数分配游标。

  这个问题是我在调用一个递归的、输出cursor output 的存储过程

create proc usp_proc(
@level int
@myref cursor varying output
)
as
begin
if @level=3
begin
set @myref=cursor local static for
select * from table
open @myref
end
if @level<3
begin
declare @cur cursor
exec usp_proc 2 @cur output --递归
--
--对输出游标@cur做一些操作
--
--使用完游标
close @cur --关闭游标
deallocate @cur --删除游标
end
end

如果没有对输出的游标做close、deallocate处理就会出现上面错误。

2.

  没有为@cur,分配游标

  这个问题是我在使用存储过程返回的游标 cursor output 产生的

  

create proc myproc(
@mycur cursor varying output
)
as
begin
set @mycur=cursor local static for
select * from table open @mycur --打开游标
end --调用myproc
declare @cur cursor
exec myproc @cur output
fetch next from @cur
while @@fetch_status=0
begin
--使用游标
fetch next from @cur
end

出现上述错的原因就是定义游标后需要打开 open @mycur