Re: create table sintax

From: Taras Kopets <tkopets(at)gmail(dot)com>
To: Júlio Almeida <julio(dot)augusto(dot)almeida(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: create table sintax
Date: 2011-04-19 13:18:52
Message-ID: BANLkTinmz6=4s4Zi3vpszpH6dCJ39fFHfg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

2011/4/19 Júlio Almeida <julio(dot)augusto(dot)almeida(at)gmail(dot)com>
> If I run
> create table newtable (like oldtable including constraints);
> in the SQL window with works just file.
> But if i execute
> execute 'create table '||newtable||' (LIKE '||oldtable||' including constraints)';
> inside a function, in a LOOP, the constraints aren't created.
> What is the problem?

You probably missing something in your function.
Please find a simple example that shows how to create a table like
other table using function.

Remember to use *quote_ident* function when you use database
identifiers in dynamic SQL's.

BEGIN;

CREATE TABLE original (
  a integer,
  b text,
  c date,
  CONSTRAINT orginal_ck_text_has_dog CHECK (position('dog' in b) <> 0),
  CONSTRAINT orginal_ck_date_is_recent CHECK (c >= '2000-01-01'::date)
  );

insert into original(a, b, c) VALUES(1, 'hot dog', now());
/* error, as expected
insert into original(a, b, c) VALUES(2, 'hot cat', now());
*/

-- function to copy other table with constraints
CREATE OR REPLACE FUNCTION create_table_like(p_orig_table text,
p_new_table text)
RETURNS VOID AS $BODY$
BEGIN
    EXECUTE 'CREATE TABLE '||quote_ident(p_new_table)
          ||' (LIKE '||quote_ident(p_orig_table)||' including constraints)';
    RETURN;
END;
$BODY$
LANGUAGE plpgsql VOLATILE STRICT;

-- execute function to create a new table like old one
SELECT create_table_like('original'::text, 'copied'::text);

insert into copied(a, b, c) VALUES(1, 'hot dog', now());
/* error, as expected
insert into copied(a, b, c) VALUES(2, 'hot cat', now());
*/
-- ROLLBACK;

Hope this helps,
Taras Kopets

In response to

Browse pgsql-general by date

  From Date Subject
Next Message giova 2011-04-19 13:39:23 how to force an insert before Raise Exception?
Previous Message mark 2011-04-19 13:17:05 Re: How to configure a read-only database server and session? (Was: read-only UNLOGGED tables)