2012-03-28 22 views
8

Postgres 9.1'de basit tablo oluşturma komut dosyası var. 2 öznitelikli PK ile tablo oluşturmak için sadece mevcut değilse buna ihtiyacım var.Sadece mevcut değilse PostgreSQL tablosuna birincil anahtar ekleyin

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. 

Bu sorunun çözümünde herhangi bir çözüm var mı? Şimdiden teşekkürler. ancak a_horse_with_no_name anlaşılacağı gibi oluşturmak tabloda dahil etmeyi iyidir,

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) 
) 

cevap

8

Neden oluşturulan tablonun içine PK tanımını içermez.

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; 
+0

Teşekkürler, aradığım şey buydu. OLMADIĞINIZ EK ADIM ÖNCESİ ANAHTARI imkansız mı? –

+2

Hayır, "ALTER TABLE" ifadesi için "IF EXSTS" seçeneği yoktur. –

7

Sen Aşağıdaki gibi bir şey yapabileceğini:

İlgili konular