2012-03-28 13 views
8

Tengo un script de creación de tabla simple en Postgres 9.1. Lo necesito para crear la tabla con 2 atributos PK solo si no existe.Agregar clave principal a la tabla PostgreSQL solo si no existe

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. 

¿Alguna solución para solucionar este problema? Gracias por adelantado.

Respuesta

8

por qué no incluir la definición de PK dentro de la tabla CREAR:

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

Gracias, eso es lo que estaba buscando. ¿Separar ADD PRIMARY KEY IF NOT EXISTS es imposible? –

+2

No, no existe la opción 'IF NOT EXISTS' para la instrucción' ALTER TABLE'. –

7

Se podría hacer algo como lo siguiente, sin embargo, es mejor incluirlo en la tabla crear a_horse_with_no_name sugiere.

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; 
Cuestiones relacionadas