I need to dynamically create a table everyday. Currently, this is my working solution:
DO
$$
BEGIN
EXECUTE format('
CREATE TABLE schema.%I (
id NUMERIC,
field1 TEXT,
field2 TEXT
)
WITH (
OIDS=FALSE
);
GRANT ALL ON TABLE schema.%I TO role1;
GRANT ALL ON TABLE schema.%I TO role2;',
'table_name_' || to_char(CURRENT_DATE,'YYYYMMDD'),
'table_name_' || to_char(CURRENT_DATE,'YYYYMMDD'),
'table_name_' || to_char(CURRENT_DATE,'YYYYMMDD')
);
END;
$$ LANGUAGE plpgsql;
However, you can see how I have to add an argument to format command for every mention of the table I'm trying to create. Add some constraints, indexes, etc., and this becomes untenable.
How can I accomplish this by setting the table name variable once and then using that over and over again? Ideally, I would like the solution to be executable from within a PGAdmin query window. That being said, however, this will end up being stored in a sql file and executed from a script.
I've tried the /set thing I've seen all over while searching for a solution, but I always end up with a syntax error starting with the slash.