if列上的主键存在语法错误

时间:2018-11-22 15:44:06

标签: sql postgresql

我想添加一列,如果表上尚不存在该列,则它也是主键。如果我做一个简单的

ALTER TABLE webinars_identities ADD COLUMN IF NOT EXISTS id uuid

可以,但是如果我可以

ALTER TABLE webinars_identities ADD COLUMN IF NOT EXISTS id uuid PRIMARY KEY DEFAULT uuid_generate_v4();

它说它跳过了alter table,但是由于某种原因在之后崩溃了:

NOTICE:  column "id" of relation "webinars_identities" already exists, skipping
ERROR:  multiple primary keys for table "webinars_identities" are not allowed

我原来的工作查询是

ALTER TABLE webinars_identities id uuid PRIMARY KEY DEFAULT uuid_generate_v4();

但这不能无误地重复。

我在这里做什么错了?

3 个答案:

答案 0 :(得分:1)

使用duplicate_column异常处理它并发出通知,因为有人正确地说过错误绝不能静默传递。

DO $body$ 
 BEGIN 
    ALTER TABLE atable ADD COLUMN  id int primary key; --DEFAULT uuid_generate_v4()
 EXCEPTION
 WHEN duplicate_column THEN

  RAISE NOTICE 'ERROR: %,%',SQLSTATE,SQLERRM;

END $body$;

这将是第一次运行,并且不会在以后的所有尝试中失败,但是会给您一条消息。如果您在对帐单中发现其他所有错误,则会引发异常。

NOTICE:  ERROR: 42701,column "id" of relation "atable" already exists
DO

答案 1 :(得分:0)

尝试一下。

DO $$ BEGIN TABLE atable ADD COLUMN IF NOT EXISTS id int primary key ; exception when others then null ; END$$;

答案 2 :(得分:0)

这是postgres https://www.postgresql.org/message-id/13277.1566920001%40sss.pgh.pa.us中的错误 希望将在v13.0中修复。