Stone 2008-6-21 12:07
如何使用fetch定位记录的问题
例如
DECLARE authors_cursor SCROLL CURSOR
FOR SELECT * FROM authors
OPEN authors_cursor
FETCH NEXT FROM authors_cursor
FETCH
从 Transact-SQL 服务器游标中检索特定的一行。
语法
FETCH
[ [ NEXT | PRIOR | FIRST | LAST
| ABSOLUTE { n | @nvar }
| RELATIVE { n | @nvar }
]
FROM
]
{ { [ GLOBAL ] cursor_name } | @cursor_variable_name }
[ INTO @variable_name [ ,...n ] ]
参数
NEXT
返回紧跟当前行之后的结果行,并且当前行递增为结果行。如果 FETCH NEXT 为对游标的第一次提取操作,则返回结果集中的第一行。NEXT 为默认的游标提取选项。
PRIOR
返回紧临当前行前面的结果行,并且当前行递减为结果行。如果 FETCH PRIOR 为对游标的第一次提取操作,则没有行返回并且游标置于第一行之前。
FIRST
返回游标中的第一行并将其作为当前行。
LAST
返回游标中的最后一行并将其作为当前行。
ABSOLUTE {n | @nvar}
如果 n 或 @nvar 为正数,返回从游标头开始的第 n 行并将返回的行变成新的当前行。如果 n 或 @nvar 为负数,返回游标尾之前的第 n 行并将返回的行变成新的当前行。如果 n 或 @nvar 为 0,则没有行返回。n 必须为整型常量且 @nvar 必须为 smallint、tinyint 或 int。
RELATIVE {n | @nvar}
如果 n 或 @nvar 为正数,返回当前行之后的第 n 行并将返回的行变成新的当前行。如果 n 或 @nvar 为负数,返回当前行之前的第 n 行并将返回的行变成新的当前行。如果 n 或 @nvar 为 0,返回当前行。如果对游标的第一次提取操作时将 FETCH RELATIVE 的 n 或 @nvar 指定为负数或 0,则没有行返回。n 必须为整型常量且 @nvar 必须为 smallint、tinyint 或 int。
声明 SCROLL 游标并使用其它 FETCH 选项
下例创建一个 SCROLL 游标,使其通过 LAST、PRIOR、RELATIVE 和 ABSOLUTE 选项支持所有滚动能力。
USE pubs
GO
-- Execute the SELECT statement alone to show the
-- full result set that is used by the cursor.
SELECT au_lname, au_fname FROM authors
ORDER BY au_lname, au_fname
-- Declare the cursor.
DECLARE authors_cursor SCROLL CURSOR FOR
SELECT au_lname, au_fname FROM authors
ORDER BY au_lname, au_fname
OPEN authors_cursor
-- Fetch the last row in the cursor.
FETCH LAST FROM authors_cursor
-- Fetch the row immediately prior to the current row in the cursor.
FETCH PRIOR FROM authors_cursor
-- Fetch the second row in the cursor.
FETCH ABSOLUTE 2 FROM authors_cursor
-- Fetch the row that is three rows after the current row.
FETCH RELATIVE 3 FROM authors_cursor
-- Fetch the row that is two rows prior to the current row.
FETCH RELATIVE -2 FROM authors_cursor
CLOSE authors_cursor
DEALLOCATE authors_cursor
GO