请问怎么将游标中的数据一个个赋值给变量,请问一下你们这个专业团队。谢谢

declare aa_cursor cursor
for select name from sysobjects where xtype = 'u'
open aa_cursor
fetch next from aa_cursor into @a
while(????)
-- 我要操作的语句
fetch next from aa_cursor into @a
end
close aa_cursor
deallocate aa_cursor

用 fetch next from aa_cursor into @a 是将一个表名赋值给变量@a 还是将游标中所有的表名都赋值给变量@a ?如果是一个表名那么是第一个还是哪一个?
还有就是循环的语句怎么写?
每一个循环里面需要操作的数据是一个表名,并且是按顺序来,一个一个的将其操作。
怎么没人回答呢??

1.用 fetch next from aa_cursor into @a 是将一个表名赋值给变量@a 还是将游标中所有的表名都赋值给变量@a ?——是将游标中所有的表名都依次赋值给@a,从第一个表名到最后一个表名

2.如果是一个表名那么是第一个还是哪一个?——因为是依次赋值给@a,所以是最后一个表名,也就是你的select name from sysobjects where xtype = 'u'这条语句取出的最后一个表名

3.还有就是循环的语句怎么写?——游标本身就是一个循环了,你的语句里面while下面写的语句,就是在循环中的语句,就是你想要的“每一个循环里面需要操作的数据是一个表名,并且是按顺序来,一个一个的将其操作”。循环条件多为while @@FETCH_STATUS = 0,也就是说取不到数据了之后就跳出这个循环。

还有其他问题和不明白的地方吗?
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-08-19
首先你要理解游标的含义,游标不是一个表名,而是一条记录的缓存
也就是说,aa_cursor 实际上是你用select查询出来的第一条记录,而且它是动态的,
利用循环,可以将每一条记录的一个或多个字段赋值给某个变量,从而达到动态查表的目的。
while(????)
是循环条件,也就是说,你要循环几次,在ORACLE中可以直接写
while(SQL%FOUND)作为循环,意思当游标有记录就继续循环,不过在SQLSERVER里没试过
还有一个最简单的办法,就是查询出你有多少条记录,然后你新建一个变量
select count(name) into 变量名 from sysobjects where xtype = 'u' group by name
然后用这个变量作为条件
while(变量名=0)
……
变量名=变量名-1
……
原理就是你用游标没操作一条记录,这个变量就自减1,直到操作完所有游标的记录,就退出循环。

试试吧~
第2个回答  2011-08-19
--没有回答是因为没有看到,先告诉你第一个问题,如果用一个变量来存,最后变量的结果是查询的最后一个表名

declare @a nvarchar(20)
declare aa_cursor cursor for select name from sysobjects where xtype = 'u' order by 1
open aa_cursor
fetch next from aa_cursor into @a
while(@@fetch_status=0)
begin
fetch next from aa_cursor into @a
end
close aa_cursor
deallocate aa_cursor

select @a

--如果要知道全部表名,这样写,请把以下代码和上边的分开执行
create table tabName(name nvarchar(50))

declare @a nvarchar(50)
declare aa_cursor cursor for select name from sysobjects where xtype = 'u' order by 1
open aa_cursor
fetch next from aa_cursor into @a
insert tabName values(@a)
while(@@fetch_status=0)
begin
fetch next from aa_cursor into @a
insert tabName values(@a)
end
close aa_cursor
deallocate aa_cursor

select * from tabName
第3个回答  2011-08-19
declare aa_cursor cursor
for select name from sysobjects where xtype = 'u'
open aa_cursor
fetch next from aa_cursor into @a
while @@FETCH_STATUS = 0
begin
set 变量 = @a
fetch next from aa_cursor into @a
end
close aa_cursor
deallocate aa_cursor

fetch next from aa_cursor into @a 是将一个表名赋值给变量@a
相似回答