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.
Code
-- 服务端游标逐行处理: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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- `work_items`, `retry_cursor` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.