postgresql 如何将`now()`作为SQL插入语句的一部分?

2wnc66cl  于 4个月前  发布在  PostgreSQL
关注(0)|答案(3)|浏览(70)

我有一个这样的SQL语句:

insert into table1 (col1, col2, col3, col4)
select
    value1,
    value2,
    now(),
    now()
from
    othertable inner join anotherothertable on somecolumn = someothercolumn;

字符串
此查询的select组件将返回数十万行。
now()的调用的行为如何?

  • 它是否会为所有行插入返回相同的值?
  • 如果在每一行插入中调用它两次,那么它是否会在同一插入中返回相同的值?

我希望执行此插入操作时,只调用一次now(),并且该值是固定的,并在插入所有行和数据时使用。我不确定此查询是否会以这种方式运行。
由于没有办法在SQL中执行类似current_timestamp = now()的操作,也没有办法使用current_timestamp作为参数来代替对now()的两个调用,因此我不确定如何执行此操作。

rryofs0p

rryofs0p1#

这在Date/Time Functions and Operators中有详细的说明,但本质上,如果您的意图是在每行中具有相同的时间,那么您的代码就很好。它将为每个单独的语句返回相同的值,甚至整个事务。
你可以做一个快速测试:

START TRANSACTION;

SELECT now();
-- Wait a few seconds
SELECT now();

ROLLBACK;

个字符

rdrgkggo

rdrgkggo2#

在语句中对函数“now”的调用为语句中的所有行返回相同的时间。返回的时间是当前事务的启动时间,即当前语句或事务中较早的语句的时间。
Postgres手册9.9.5. Current Date/Time中有相关文档。
下面是一个总结:
| 功能|标准的?|几点?|
| --|--|--|
| 当前日期|是的|交易|
| 当前时间|是的|交易|
| 当前_时间戳|是的|交易|
| CURRENT_TIME(精度)|是的|交易|
| CURRENT_TIMESTAMP(精度)|是的|交易|
| LOCALTIME|是的|交易|
| 本地时间戳|是的|交易|
| LOCALTIME(精度)|是的|交易|
| LOCALTIMESTAMP(精度)|是的|交易|
| transaction_timestamp()|没有|交易|
| statement_timestamp()|没有|声明|
| 时钟时间戳|没有|时钟时间|
| TimeOfDay|没有|时钟时间|
| Now()|没有|交易|
所以,你不需要把时间放在一个“变量”中。如果出于某种原因,你仍然想这样做,你可以在一个公共表表达式(WITH查询)的帮助下将时间隔离到一个“变量”中,而不需要离开SQL:

WITH my_time(t) AS ( VALUES (now()) )
insert into table1 (col1, col2, col3, col4)
select
    value1,
    value2,
    t,
    t
from my_time,
     othertable
join anotherothertable on somecolumn = someothercolumn

字符串

8yparm6h

8yparm6h3#

声明和使用变量是最好的选择IMHO。

create table table1 (col1 int, col2 int, col3 timestamp, col4 timestamp);

DO $$
 DECLARE _now timestamp;
 
BEGIN
  select now() into _now;
  
insert into table1 (col1, col2, col3, col4)
select
    x.v,
    x.v*10,
    _now,
    _now
from
    generate_series(1, 10) x(v);
END $$;

select * from table1;

字符串
| col1| col2| col3| col4|
| --|--|--|--|
| 1 | 10 |2023-12-20 11:35:43.987329| 2023-12-20 11:35:43.987329|
| 2 | 20 |2023-12-20 11:35:43.987329| 2023-12-20 11:35:43.987329|
| 3 | 30 |2023-12-20 11:35:43.987329| 2023-12-20 11:35:43.987329|
| 4 | 40 |2023-12-20 11:35:43.987329| 2023-12-20 11:35:43.987329|
| 5 | 50 |2023-12-20 11:35:43.987329| 2023-12-20 11:35:43.987329|
| 6 | 60 |2023-12-20 11:35:43.987329| 2023-12-20 11:35:43.987329|
| 7 | 70 |2023-12-20 11:35:43.987329| 2023-12-20 11:35:43.987329|
| 8 | 80 |2023-12-20 11:35:43.987329| 2023-12-20 11:35:43.987329|
| 9 | 90 |2023-12-20 11:35:43.987329| 2023-12-20 11:35:43.987329|
| 10 | 100 |2023-12-20 11:35:43.987329| 2023-12-20 11:35:43.987329|
DBFiddle demo

相关问题