Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create function to create table Postgresql

Tags:

postgresql

I am trying to create table inside POSTGRESQL function but getting following error.

ERROR: no schema has been selected to create in CONTEXT: SQL statement " CREATE TABLE IF NOT EXISTS test.t_testing ( id serial PRIMARY KEY, customerid int, daterecorded date, value double precision )"

My function is as follows.

CREATE OR REPLACE FUNCTION test.create_table_type1(t_name varchar(30))
  RETURNS VOID AS
$func$
BEGIN

EXECUTE format('
   CREATE TABLE IF NOT EXISTS %I (
    id serial PRIMARY KEY,
    customerid int,
    daterecorded date,
    value double precision
   )', 'test.t_' || t_name);

END
$func$ LANGUAGE plpgsql;
like image 902
karan Avatar asked Aug 08 '26 03:08

karan


1 Answers

Try this instead:

CREATE OR REPLACE FUNCTION test.create_table_type1(t_name varchar(30))
  RETURNS VOID AS
$func$
BEGIN

EXECUTE format(
    'CREATE TABLE IF NOT EXISTS %I.%I (
        id serial       PRIMARY KEY,
        customerid      int,
        daterecorded    date,
        value           double precision
    )',
   'test',
   ( 't_' || t_name )
);

END
$func$ LANGUAGE plpgsql;

So sepparate 'schema' and 'table'.

like image 104
Kristo Mägi Avatar answered Aug 10 '26 18:08

Kristo Mägi