2012-03-28 9 views
8

Ho uno script di creazione di tabelle semplice in Postgres 9.1. Mi serve per creare la tabella con PK a 2 attributi solo se non esiste.Aggiungere la chiave primaria alla tabella PostgreSQL solo se non esiste

CREATE TABLE IF NOT EXISTS "mail_app_recipients" 
(
    "id_draft" Integer NOT NULL, 
    "id_person" Integer NOT NULL 
) WITH (OIDS=FALSE); -- this is OK 

ALTER TABLE "mail_app_recipients" ADD PRIMARY KEY IF NOT EXISTS ("id_draft","id_person"); 
-- this is problem since "IF NOT EXISTS" is not allowed. 

Qualche soluzione su come risolvere questo problema? Grazie in anticipo.

risposta

8

Perché non includere la definizione PK all'interno del CREATE TABLE:

CREATE TABLE IF NOT EXISTS mail_app_recipients 
(
    id_draft Integer NOT NULL, 
    id_person Integer NOT NULL, 
    constraint pk_mail_app_recipients primary key (id_draft, id_person) 
) 
+0

Grazie, questo è quello che stavo cercando. Separare ADD PRIMARY KEY SE NON ESISTE è impossibile? –

+2

No, non esiste l'opzione 'SE NON ESISTE' per l'istruzione' ALTER TABLE'. –

7

Si potrebbe fare qualcosa di simile a quanto segue, tuttavia è meglio includere nella tabella creare a_horse_with_no_name suggerisce.

if NOT exists (select constraint_name from information_schema.table_constraints where table_name = 'table_name' and constraint_type = 'PRIMARY KEY') then 

ALTER TABLE table_name 
    ADD PRIMARY KEY (id); 

end if; 
Problemi correlati