sql server中for循环的应用
每个公司都有不同的数据库,最近用sql server时,正想使用游标for循环时,发现sqlserver并没有像Oracle那样的for循环,查阅了相关资料,以下是sql server的实现方式
declare @id int,@name varchar(20),@lass varchar(20)
declare student_cursor cursor
for(select id ,name ,class from student)
open student_cursor
fetch next from student_cursor into @id ,@name,@lass
while @@FETCH_STATUS=0
begin
insert into #temp
select * from student where id=@id
fetch next from student_cursor into @id ,@name,@lass
end
close student_cursor
deallocate student_cursor
首先定义该游标,这个大家都懂
declare student_cursor cursor
for(select id ,name ,class from student)
然后打开游标,把游标值插入变量中
open student_cursor
fetch next from student_cursor into @id ,@name,@lass
然后用while循环和 @@FETCH_STATUS全局变量来判断游标的状态
while @@FETCH_STATUS=0
@@fetch_status有以下三种,分别表示三种不同含义:【返回类型integer】
- 0 FETCH 语句成功
-1 FETCH 语句失败或此行不在结果集中
-2 被提取的行不存在
因此,返回0则继续循环
然后,进入到程序主体部分
begin
insert into #temp
select * from student where id=@id
fetch next from student_cursor into @id ,@name,@lass
end
其中记得要,要把下个游标值赋予变量,不然会出现死循环
fetch next from student_cursor into @id ,@name,@lass
最后,记得关闭游标和释放游标
close student_cursor
deallocate student_cursor
更多推荐
sql server中for循环的应用总结
发布评论