如何将 DEFAULT 插入到 PostgreSQL 中的准备语句中

how to insert DEFAULT into a prepared statement in PostgreSQL

我正在尝试使用准备好的语句将值插入数据库,但有时我需要为某个值插入文字 'DEFAULT',我该怎么做?

CREATE TABLE test (id int, firstname text default 'john', lastname text default 'doe');

这就是我想要做的,但是使用准备好的语句:

insert into test (id, firstname, lastname) VALUES ('1', DEFAULT, DEFAULT);

但这会导致错误(原因很明显):

PREPARE testprep (integer, text, text) AS INSERT INTO test (id, firstname, lastname) VALUES (, , );
EXECUTE testprep('1',DEFAULT,DEFAULT);

错误:

ERROR: syntax error at or near "DEFAULT"

我使用 SQL-Fiddle:

创建的两个示例

http://sqlfiddle.com/#!15/243ae/1/0

http://sqlfiddle.com/#!15/243ae/3/0

您可以尝试从插入语句中省略默认列:

PREPARE testprep (integer) AS
INSERT INTO test (id) VALUES ();
EXECUTE testprep('1');

Postgres 应该依赖 firstnamelastname 列的 table 定义中的默认值。来自 Postgres documentation:

When a new row is created and no values are specified for some of the columns, those columns will be filled with their respective default values.

准备好的语句无法做到这一点。

唯一的转义是 table 上的 BEFORE INSERT 触发器,它用默认值替换某些数据值(例如 NULL)。但这不是一个好的解决方案,并且会降低性能。

另一种逃避方法是使用多个准备好的语句,一个用于您要设置为默认值的每种组合。