Sqlserver使用游标应用遍历实例

--申明一个游标
DECLARE MyCursor CURSOR
FOR SELECT TOP 5 FBookName,FBookCoding FROM TBookInfo

--打开一个游标
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

 


例子:

DECLARE MyCursor CURSOR
FOR SELECT top 5 ClientCode FROM Client --5个客户的编号作为变量

--打开一个游标
OPEN MyCursor

--循环一个游标
DECLARE @ClientCode nvarchar(2000)
FETCH NEXT FROM MyCursor INTO @ClientCode
WHILE @@FETCH_STATUS =0
BEGIN
  print ‘name‘+@ClientCode

  --查询语句
FETCH NEXT FROM MyCursor INTO @ClientCode
END

--关闭游标
CLOSE MyCursor
--释放资源
DEALLOCATE MyCursor

/*
结果:
name100001
name100002
name100003
name100004
name100005
*/

Sqlserver使用游标应用遍历实例

上一篇:flea-frame-db使用之JPA封装介绍


下一篇:1、postgresql在centos7.6tar包安装