【问题标题】:How to use DEFAULT in postgres? [duplicate]如何在 postgres 中使用 DEFAULT? [复制]
【发布时间】:2019-06-07 01:46:28
【问题描述】:

我有表和函数:

create table test_temporal (
  id SERIAL,
  name varchar(16)
);

create or replace function test_temporal_insert()
returns trigger as $$
begin
INSERT INTO test_temporal ( id, name )
values ( coalesce( new.id, DEFAULT ), new.name );
return NEW;
end;
$$ language plpgsql;

但是当我尝试插入时出现错误:

insert into test ( name ) values ( 'a' );

ERROR:  DEFAULT is not allowed in this context
LINE 2: values ( coalesce( new.id, DEFAULT ), new.name )
                                   ^
QUERY:  INSERT INTO test_temporal ( id, name )
values ( coalesce( new.id, DEFAULT ), new.name )
CONTEXT:  PL/pgSQL function test_temporal_insert() line 3 at SQL statement

在我的触发器中,如果用户没有为id 提供值,我需要从序列 (DEFAULT) 生成下一个值。如果用户为id 提供价值,我应该使用它 (new.id)

如果没有提供new.id,如何插入DEFAULT 值?

dbfiddle

【问题讨论】:

  • 创建表时需要添加默认值。参考:postgresql.org/docs/9.3/ddl-default.html
  • @KaushikNayak:select version(); PostgreSQL 10.4 (Debian 10.4-2.pgdg90+1)
  • 它在 10.6 中工作,请参阅 dbfiddle 。如果您删除 coalesce,它将在旧版本中编译 9.6 demo
  • @KaushikNayak: it 没有
  • 您也可以添加您的触发代码吗?

标签: postgresql plpgsql database-trigger


【解决方案1】:

我通过条件解决了这个问题:

create or replace function test_temporal_insert()
returns trigger as $$
begin
IF( new.id is null ) THEN
  INSERT INTO test_temporal ( name )
  values ( new.name );
ELSE
  INSERT INTO test_temporal ( id, name )
  values ( new.id, new.name );
END IF;
return NEW;
end;
$$ language plpgsql;

如果 Postgresql 允许coalesce( new.id, DEFAULT ),那就很清楚了:

INSERT INTO test_temporal ( id, name )
values ( coalesce( new.id, DEFAULT ), new.name );

【讨论】:

  • 您可以在没有coalesce 的情况下明确指定默认值,例如this
  • @KaushikNayak:是的,但还有IF THEN ELSE block =(
猜你喜欢
  • 2011-04-12
  • 1970-01-01
  • 2021-03-16
  • 2017-10-30
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 2015-08-31
  • 2018-05-18
相关资源
最近更新 更多