关于数据库游标的例子

来源:互联网 发布:准确的日语翻译软件 编辑:程序博客网 时间:2024/06/06 21:06

declare @tableName nvarchar(100),@tbID int

declare cur cursor  for--创建游标
select name,id from sysobjects where xtype= 'U'

open cur --打开游标
print '行数:'+convert(nvarchar(4),@@CURSOR_ROWS )
print '表名   表ID '
fetch next from cur into @tableName,@tbID--fetch....into  使用游标
while @@fetch_status=0 
begin
 print @tableName+'   '+convert(nvarchar(20),@tbID)
 fetch next from cur into @tableName,@tbID
end
close cur --关闭游标
deallocate cur--释放,卸载游标(若下次使用要重新声明)

-----------------------------结果------------------------

行数:-1
表名   表ID
tb   21575115
a表   69575286
b表   85575343
sysdiagrams   213575799
temp   373576369
Table_1   2073058421
----------------------------------------------------------

 

这个是游标的例子,参考SqlServer联机丛书

@@CURSOR_ROWS在open之后执行,返回为查询的行数

但上面结果为“行数:-1”

发现其中原因为cursor类型不正确,该游标为动态游标。因为动态游标可反映所有更改,所以游标符合条件的行数不断变化。因此,永远不能确定已检索到所有符合条件的行。

---------------------------参考-----------------------------

-m
游标被异步填充。返回值 (-m) 是键集中当前的行数。

-1
游标为动态游标。因为动态游标可反映所有更改,所以游标符合条件的行数不断变化。因此,永远不能确定已检索到所有符合条件的行。

0
没有已打开的游标,对于上一个打开的游标没有符合条件的行,或上一个打开的游标已被关闭或被释放。

n
游标已完全填充。返回值 (n) 是游标中的总行数。

------------------------------------------------------------

可修改为如下两种cursor方式

declare cur cursor scroll for........

declare cur cursor static for........

 

修改后正确结果为

-----------------------------结果------------------------

行数:6
表名   表ID
tb   21575115
a表   69575286
b表   85575343
sysdiagrams   213575799
temp   373576369
Table_1   2073058421

----------------------------------------------------------

 

原创粉丝点击