SQL 游标 自己写的一个小例子 帮找一下错误

来源:百度知道 编辑:UC知道 时间:2024/05/31 17:37:00
SET NOCOUNT ON

declare @cur_tab varchar(30)

declare cur_name cursor for
select name from sysobjects where type='U'
open cur_name
fetch next from cur_name into @cur_tab
while @@fetch_status = 0

close cur_name

运行时总提示“游标未打开” ???

还有就是如何在这个过程运用临时表

谢谢!

提示“游标未打开” 是因为你的WHILE循环里面没有东西,系统就把CLOSE CUR_NAME默认为是你的循环体,所以一致执行close cur_name ,当然就会一致提示游标未打开

运用临时的话要具体情况具体分析 看你的需求

declare @cur_tab varchar(30)
declare @table table(tablename varchar(50))
declare cur_name cursor for
select name from sysobjects where type='U'
open cur_name
fetch next from cur_name into @cur_tab
while(@@fetch_status = 0)
begin
insert into @table(tablename)
values(@cur_tab)
fetch next from cur_name into @cur_tab
end
close cur_name
deallocate cur_name

declare @cur_tab varchar(30)
declare @table table(tablename varchar(50))
declare cur_name cursor for
select name from sysobjects where type='U'
open cur_name
fetch next from cur_name into @cur_tab
while(@@fetch_status = 0)
begin
insert into @table(tablename)
values(@cur_tab)
fetch next from cur_name into @cur_tab
end
close cur_name