SQL Server游标语句使用方法:
复制代码 代码如下:
--声明一个游标
DECLARE MyCursor CURSOR
FOR SELECT TOP 5 FBookName,FBookCoding FROM TBookInfo//定义一个叫MyCursor的游标,存放for select 后的数据
--打开一个游标
OPEN MyCursor//即打开这个数据集
--循环一个游标
DECLARE @BookName nvarchar(2000),@BookCoding nvarchar(2000)
FETCH NEXT FROM MyCursor INTO @BookName,@BookCoding//移动游标指向到第一条数据,提取第一条数据存放在变量中
WHILE @@FETCH_STATUS =0//如果上一次操作成功则继续循环
BEGIN
print 'name'+@BookName
FETCH NEXT FROM MyCursor INTO @BookName,@BookCoding//继续提下一行
END
--关闭游标
CLOSE MyCursor
--释放资源
DEALLOCATE MyCursor
eg:
复制代码 代码如下:
create table #a
(
id varchar(20),
name varchar(20)
)
insert into #a select 1,'jack'
insert into #a select 2,'join'
insert into #a select 3,'make'
declare mycursor cursor
for select * from #a
open mycursor
declare @id varchar(20),@name varchar(20)
fetch next from mycursor into @id,@name
while @@fetch_status=0
begin
select @id,@name
fetch next from mycursor into @id,@name
end
close mycursor
deallocate mycursor