簡體   English   中英

僅在主表不存在時才將主鍵添加到PostgreSQL表

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

我在Postgres 9.1中有簡單的表創建腳本。 我需要它來創建具有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.

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

為什么不在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)
)

您可以執行以下操作,但最好將其包含在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;

您可以在創建它之前嘗試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");

請注意,這需要您為主鍵約束命名 - 在此示例中為mail_app_recipients_pkey

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM