Sql Server游标小记
declare cursor_school CURSOR LOCAL FAST_FORWARD 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.在执行完后,请记得关闭游标和释放游标。
3.记得要加上Local,因为默认为全局游标,需要显示释放并且多session同时访问时会报错。为了减少各种异常建议声明为local类型。
浙公网安备 33010602011771号