2012-03-28 63 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;