Faustas - Programming, Projects, Psychology and Faust
I needed a way to search for specific tables in Postgres. The following stored procedure searches for tables that match the given regular expression.
The following procedure has two parameters. The first parameter is the name of the schema where the script is searching for the tables. The second parameter is the specific regular expression that will be used to search for the tables in the specified schema.
The function returns the names of the tables that contain the regular expression.
The code looks as follows:
-- Function: myschema.list_tables(character varying, character varying) -- DROP FUNCTION myschema.list_tables(character varying, character varying); CREATE OR REPLACE FUNCTION myschema.list_tables(_schema_ character varying, _table_regexp_ character varying) RETURNS SETOF character varying AS $BODY$ DECLARE result VARCHAR := ''; BEGIN FOR result IN SELECT table_name FROM information_schema.tables WHERE table_schema = $1 AND table_name ~* $2 ORDER BY table_name LOOP RETURN NEXT result; END LOOP; RETURN; END; $BODY$ LANGUAGE 'plpgsql' VOLATILE COST 100 ROWS 1000;
The $1 and $2 variables in the code refer to the two parameters _schema_ and _table_regexp_.
May it can help you.