In my Postgres 9.2 database I've got the following SELECT, which will be used by a PL/pgSQL function:
SELECT
id
FROM
tablea
WHERE
migrated = false;
I want to get 2000 records each time and perform something like the following:
CREATE or REPLACE FUNCTION migrate_data()
RETURNS integer AS
$$
declare
row record;
BEGIN
FOR row IN EXECUTE '
SELECT
id
FROM
tablea
WHERE
migrated = false
'
LOOP
INSERT INTO tableb (id)
VALUES (row.id);
UPDATE tablea a SET migrated = yes WHERE a.id = row.id;
END LOOP;
RETURN num_rows; -- I want it to return the number of processed rows
END
$$ language 'plpgsql';
How can I tell the function to process 2000 records with every call? And it must start from where it left when on the next call.
Example:
select migrate_data(); -- id 0 to id 2000
select migrate_data(); -- id 2001 to id 4000
select migrate_data(); -- id 4001 to id 6000
select migrate_data(); -- id 6001 to id 8000
Etc.