第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