Can you do this. Use the INTO keyword in an EXECUTE statement .
CREATE OR REPLACE FUNCTION grow(_col text, OUT tmp integer) AS $func$ BEGIN EXECUTE format( 'UPDATE stats SET %I = %I + 1 RETURNING %I' , _col) INTO tmp; END $func$ LANGUAGE plpgsql;
Call:
SELECT grow('counter');
Using the OUT parameter for simplification in general.
format() syntax described in the manual .
You can simply run UPDATE instead of calling the function:
UPDATE stats SET counter = counter + 1 RETURNING counter;
There are not many scenarios where a function with dynamic SQL is not just an unnecessary complication.
Alternative design
If possible, consider another table layout: rows instead of columns (as @Ruslan suggested). Allows any number of counters:
CREATE TABLE stats ( tag text PRIMARY KEY , counter int NOT NULL DEFAULT 0 );
Call:
UPDATE stats SET counter = counter + 1 WHERE tag = 'counter1' RETURNING counter;
Or perhaps consider highlighted SEQUENCE for counting ...
source share