HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMajor

Postgresql function to create table

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlfunctiontablecreate

Problem

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?

Solution

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.

Code Snippets

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$;

Context

StackExchange Database Administrators Q#42924, answer score: 27

Revisions (0)

No revisions yet.