简体   繁体   English

仅在主表不存在时才将主键添加到PostgreSQL表

[英]Add primary key to PostgreSQL table only if it does not exist

I have simple table creating script in Postgres 9.1. 我在Postgres 9.1中有简单的表创建脚本。 I need it to create the table with 2-attributes PK only if it does not exist. 我需要它来创建具有2个属性PK的表,只有它不存在。

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.

Any solution how to solve this problem? 任何解决方案如何解决这个问题? Thanks in advance. 提前致谢。

Why not include the PK definition inside the CREATE TABLE: 为什么不在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)
)

You could do something like the following, however it is better to include it in the create table as a_horse_with_no_name suggests. 您可以执行以下操作,但最好将其包含在create table中,如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;

You can try to DROP it before creating it ( DROP has the IF EXISTS clause): 您可以在创建它之前尝试DROP它( DROP具有IF EXISTS子句):

ALTER TABLE mail_app_recipients DROP CONSTRAINT IF EXISTS mail_app_recipients_pkey;
ALTER TABLE mail_app_recipients ADD CONSTRAINT mail_app_recipients_pkey PRIMARY KEY ("id_draft","id_person");

Note that this require that you give a name to the primary key constraint - in this example mail_app_recipients_pkey . 请注意,这需要您为主键约束命名 - 在此示例中为mail_app_recipients_pkey

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM