英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论