declare my_cur cursor for select top 5 [name] from sys.objects where type = 'U' and type_desc = 'USER_TABLE' open my_cur declare @name varchar(50), @count bigint select @name = '', @count = 0 --Fetch next from my_cur into @name while @@fetch_status = 0 begin declare @sql nvarchar(4000) select @sql = N'select @count = count(*) from dbo.' + @name print @sql Fetch next from my_cur into @name end close my_cur deallocate my_cur
当第一个Fetch Next from ... 注释起来的时侯,一个会话第一次执行一次后可以显示结果,再次执行没有执行结果,又说执行成功完成“Command(s) completed successfully.”。Fetch取消注释后OK。@@fetch_status是全局变量,上一次执行后它的状态不是0了,之后While循环没有执行。