Sql Server游标小记

declare cursor_school cursor forward_only 
for
select name from sysobjects where type='U'and name like 'UT_IPARK%'
open cursor_school
declare @name nvarchar(100),@i int
fetch next from cursor_school into @name
while @@fetch_status=0
begin
    -- do something
    print  ''+@name
    fetch next from cursor_school into @name
end
--关闭游标
close cursor_school
deallocate  cursor_school
go

解释:

1.在while语句前,一定要添加fetch next from cursor_school into @name,否则游标在执行一次后,再次执行时无内容输出,原因是全局变量@@fetch_status在执行一次后,变为-1,这时是无法满足进入while模块条件的,因此必须添加fetch语句,使系统重置全局变量@@fetch_status。

2.在执行完后,请记得关闭游标和释放游标。

posted @ 2020-10-20 16:05  Shapley  阅读(75)  评论(0编辑  收藏  举报