【发布时间】: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 值?
【问题讨论】:
-
创建表时需要添加默认值。参考:postgresql.org/docs/9.3/ddl-default.html
-
@KaushikNayak:
select version(); PostgreSQL 10.4 (Debian 10.4-2.pgdg90+1) -
@KaushikNayak: it 没有
-
您也可以添加您的触发代码吗?
标签: postgresql plpgsql database-trigger