Postgres准备好的语句绑定`now()`。

huangapple go评论60阅读模式
英文:

Postgres prepared statement bind `now()`

问题

我有一个准备好的插入语句,其中有一个用于日期的占位符。我希望能够插入用户提供的日期,或者如果未提供日期,则回退到使用 now() 插入当前时间。是否可以绑定 now() 的结果,还是我需要使用第二个插入语句直接在语句中使用 now() 而不是占位符?
例如,我可以这样做:

PREPARE my_statement AS 
INSERT INTO my_table (date_column) 
VALUES ($1);
EXECUTE my_statement (now());

还是我需要这样做:

PREPARE my_statement AS 
INSERT INTO my_table (date_column) 
VALUES (now);
EXECUTE my_statement;
英文:

I have a prepared insert statement which has a placeholder for a date. I want to be able to insert a date provided by a user, or if it has not been provided fall back to inserting the current time using now(). Is it possible to bind the result of now() or do I need to use a second insert statement using now() directly in the statement rather than a placeholder?
For example, can I do this:

PREPARE my_statement AS 
INSERT INTO my_table (date_column) 
VALUES ($1);
EXECUTE my_statement (now());

or do I need to do this

PREPARE my_statement AS 
INSERT INTO my_table (date_column) 
VALUES (now);
EXECUTE my_statement;

答案1

得分: 1

是的。根据EXECUTE语句的文档,每个参数“必须是产生与该参数的数据类型兼容的值的表达式”。这允许使用任意表达式,如now()函数调用,而不仅仅是文字值。

英文:

> Is it possible to bind the result of now()?

Yes. According to the docs of the EXECUTE statement, each of the parameters "must be an expression yielding a value that is compatible with the data type of this parameter". This allows arbitrary expressions, such as the now() function call, not just literal values.

huangapple
  • 本文由 发表于 2023年6月5日 07:51:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定