[SQL Server]游标示例
IF(OBJECT_ID('tempdb..#Books') IS NOT NULL)
BEGIN
DROP TABLE #Books;
END
CREATE TABLE #Books
(
BookName NVARCHAR(20),
BookCode NVARCHAR(20)
)
INSERT INTO #Books( BookName, BookCode ) VALUES(N'C# 本质论','JC556874');
INSERT INTO #Books( BookName, BookCode ) VALUES(N'JS 本质论','JS556874');
--申明一个游标
DECLARE MyCursor CURSOR FOR
SELECT TOP 5 BookName,BookCode FROM #Books;
--打开一个游标
OPEN MyCursor;
DECLARE @BookName nvarchar(20);
DECLARE @BookCode nvarchar(20);
--循环一个游标
FETCH NEXT FROM MyCursor INTO @BookName,@BookCode;
WHILE(@@FETCH_STATUS = 0)
BEGIN
PRINT('Book Name: '+@BookName);
FETCH NEXT FROM MyCursor INTO @BookName,@BookCode;
END
--关闭游标
CLOSE MyCursor;
--释放资源
DEALLOCATE MyCursor;
-------------------------------------------------------------------------------------------------------------------------------------
@@FETCH_STATUS 是一个全局变量,其值有以下三种 :
1) 0 FETCH 语句成功
2) -1 FETCH 语句失败或此行不在结果集中
3) -2 被提取的行不存在