我有表格和函数:
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
在触发器中,如果用户没有为DEFAULT
提供值,则需要从序列(id
)中生成下一个值。如果用户为id
提供了价值,我应该使用它(new.id
)
在没有提供DEFAULT
的情况下如何插入new.id
值?
答案 0 :(得分:0)
我通过条件解决该问题:
['asd;1.1.1.1','sdf;2.2.2.2']
很显然Postgresql是否允许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;
:
coalesce( new.id, DEFAULT )