I need to run the same query on many tables of a DB (PostgreSQL 9.3.5) and passing the table name as an argument to a function seems a logic thing to do. Reading at examples in the docs and numerous S.O. postings, I still cannot nail it down.
Using this minimal example:
CREATE TABLE films (
code char(5),
kind varchar(10)
);
INSERT INTO films VALUES
('UA502', 'Comedy');
And this function:
CREATE OR REPLACE FUNCTION foo(_t text)
RETURNS void AS -- I know, void is not what I am after
$func$
BEGIN
EXECUTE format('SELECT count(*) FROM %I', _t);
END
$func$ LANGUAGE plpgsql;
The following query catches something:
mydb=> SELECT foo('films');
foo
-----
(1 row)
However because I want to retrieve a table I edit the second line and re-create the function like so:
CREATE OR REPLACE FUNCTION foo(_t text)
RETURNS TABLE(count integer) AS
$func$
BEGIN
EXECUTE format('SELECT count(*) FROM %I', _t);
END
$func$ LANGUAGE plpgsql;
However the same query does not catch anything:
mydb=> SELECT foo('films');
foo
-----
(0 rows)
Could someone let me know what I am missing here and how to proceed? Any hints greatly appreciated!