我可以重置光标吗's的位置从头开始



如主题中所示。在Transact-SQL中,我可以简单地将光标的位置重置为开头,这样它就可以在表上再次运行吗?我想在以下上下文中重置它:

DECLARE @userID INT
DECLARE user_cursor CURSOR FOR SELECT userID FROM users
WHILE /* some condition */
BEGIN
...
    FETCH NEXT FROM user_cursor INTO @userID
    IF @@FETCH_STATUS = 0
    BEGIN
        /*... here goes the reset of the cursor ...*/
    END
...
END

您需要将光标声明为滚动,如以下

declare c scroll cursor for (select statement); 

那么在任何时候要定位到第一个,只需使用以下

fetch first from c;

可以使用的另一个不强迫您更改光标类型的选项只是关闭光标并重新打开它:

CLOSE user_cursor
OPEN user_cursor

但是scroll选项在资源使用方面会更便宜,如果你可以接受的话。

光标检索到的数据不会更改。

静态

定义一个游标,该游标生成要由游标使用的数据的临时副本。所有对游标的请求都会从tempdb中的这个临时表中得到响应;因此,对基表所做的修改不会反映在对该游标进行的提取所返回的数据中,并且该游标不允许进行修改。

使用游标循环及其处理。。。

cursor c_something IS
   select * from somewhere
BEGIN
    for some_row in c_something LOOP
        -- do stuff with some_row.COLUMN;
    END LOOP; -- this closes the cursor for you when it has gone all the way through
    -- do other stuff
    for some_row in c_something LOOP -- opens the cursor again from the top
        -- do stuff with some_row.COLUMN;
    END LOOP;
END;

最新更新