15

I want to create a function in order to create a table with a specific structure pasing part of the name of the table as an argument so the name of the table is t_ . Similar to this:

CREATE OR REPLACE FUNCTION create_table_type1(t_name VARCHAR(30)) RETURNS VOID AS $$
BEGIN
 EXECUTE "CREATE TABLE IF NOT EXISTS t_"|| t_name ||"
 (
 id SERIAL,
 customerid INT,
 daterecorded DATE,
 value DOUBLE PRECISION,
 PRIMARY KEY (id)
 )"
END
$$ LANGUAGE plpgsql

Then call it like:

SELECT create_table_type1('one');

Is it possible?

Evan Carroll
65.7k50 gold badges259 silver badges510 bronze badges
asked May 23, 2013 at 16:19

2 Answers 2

28

Answer is yes. :)

CREATE OR REPLACE FUNCTION create_table_type1(t_name varchar(30))
 RETURNS VOID
 LANGUAGE plpgsql AS
$func$
BEGIN
 EXECUTE format('
 CREATE TABLE IF NOT EXISTS %I (
 id serial PRIMARY KEY,
 customerid int,
 daterecorded date,
 value double precision
 )', 't_' || t_name);
END
$func$;

I am using format() with %I to sanitize the table name and avoid SQL injection. Requires PostgreSQL 9.1 or above.

Be sure to use single quotes ('') for data. Double quotes ("") are for identifiers in SQL.

answered May 23, 2013 at 17:01
4
  • Thank you again, it works but you've got a little mistake. It should be 'CREATE TABLE IF NOT EXISTS %I', right? Commented May 23, 2013 at 17:17
  • @user1350102: Right, the table name goes after IF NOT EXISTS. Thanks, amended. Commented May 23, 2013 at 21:16
  • @ErwinBrandstetter, could we use $$ ... $$ LANGUAGE plpgsql; instead of $func$ ... $func$ LANGUAGE plpgsql;? What is the difference between these two? Is there a situation where one is preferable to the other? I'm wondering because I've been using the former. Commented Sep 20, 2017 at 9:57
  • 1
    @dw8547: You could. No significance. It's just dollar-quoting. See: stackoverflow.com/questions/12144284/…. I use $func$ instead of just $$ for clarity and to avoid problems with nested dollar-quoting. Commented Sep 20, 2017 at 12:47
2

yes, this is possible. however, you have to be a little careful. DDLs in a stored procedure USUALLY work. in some nasty corner cases you might end up with "cache lookup" errors. The reason is that a procedure is basically a part of a statement and modifying those system objects on the fly can in rare corner cases cause mistakes (has to be). This cannot happen with CREATE TABLE, however. So, you should be safe.

answered Oct 31, 2014 at 14:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.