2012-03-28 242 views
8

我在Postgres 9.1中有簡單的表格創建腳本。我需要它創建與 2屬性PK只有它不存在的表。僅當PostgreSQL表不存在主鍵時才添加主鍵

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. 

任何解決方案如何解決這個問題?提前致謝。

回答

8

爲什麼不包括CREATE TABLE裏面的PK定義:

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

謝謝,這就是我一直在尋找的。單獨添加主鍵如果不存在是不可能的? – 2012-03-28 11:57:03

+2

不,沒有'ALTER TABLE'語句的'IF NOT EXISTS'選項。 – 2012-03-28 11:59:06

7

你可以做類似以下,但最好是將其包含在創建表作爲a_horse_with_no_name建議。

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;