Cursor Current Of Positional Update

WHERE CURRENT OF rewrites exactly the row a declared cursor currently points at: each FETCH advances the pointer and the positional UPDATE follows it.

SqlData Integrity

Code

snippet
-- 服务端游标逐行处理:WHERE CURRENT OF 是 positional (定位) 更新,只改当前行
BEGIN;

CREATE TABLE work_items (
    id      int PRIMARY KEY,
    payload text NOT NULL,
    status  text NOT NULL DEFAULT 'queued'
);

INSERT INTO work_items (id, payload) VALUES
    (1, 'alpha'), (2, 'beta'), (3, 'gamma');

-- FOR UPDATE 声明行会被本游标更新,配合 WHERE CURRENT OF 使用
DECLARE retry_cursor CURSOR FOR
    SELECT id, payload FROM work_items WHERE status = 'queued' FOR UPDATE;

FETCH NEXT FROM retry_cursor;          -- 第 1 行
UPDATE work_items SET status = 'done'
WHERE CURRENT OF retry_cursor;         -- 只更新游标当前指向的行

FETCH NEXT FROM retry_cursor;          -- 第 2 行
UPDATE work_items SET status = 'failed'
WHERE CURRENT OF retry_cursor;

CLOSE retry_cursor;
COMMIT;

SELECT id, payload, status FROM work_items ORDER BY id;

DROP TABLE work_items;

Inside the snippet

What runs here is SELECT / INSERT / UPDATE / CREATE — work_items and retry_cursor are the objects involved.

Breaking the statements into their working parts: a WHERE clause filtering the rows one statement applies to; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Using it

The work_items table is the working surface here.

Key statements

DECLARE retry_cursor CURSOR FOR
    SELECT id, payload FROM work_items WHERE status = 'queued' FOR UPDATE;
UPDATE work_items SET status = 'done'
WHERE CURRENT OF retry_cursor;         -- 只更新游标当前指向的行
UPDATE work_items SET status = 'failed'
WHERE CURRENT OF retry_cursor;

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`work_items`, `retry_cursor` — referenced directly, no join needed.