I'd like to loop through a list of postgresql databases and run some queries on them from within a postgresql function. Here's a code example...
CREATE OR REPLACE FUNCTION my_function()
RETURNS VOID AS
$$
DECLARE
db VARCHAR(50); -- this declaration is where the confusion is
BEGIN
FOR db IN
SELECT datname FROM pg_catalog.pg_database WHERE datname ~ '^mydbname_'
LOOP
-- this is just an example
SELECT * FROM db;
END LOOP;
END;
$$
LANGUAGE 'plpgsql';
I'm aware that I can use postgresql's EXECUTE to evaluate the queries as a string (e.g., EXECUTE 'SELECT * FROM ' || db || ';';), but my queries are rather long and complex.
Is there a way to do this in postgresql? Is there a "database" declaration type?