7

如果我做

INSERT INTO table1 (datetime1, datetime2) VALUES (NOW(),NOW())

这两个字段在两列中是否总是相同的?

同上

INSERT INTO table1 (datetime1, datetime2) VALUES (NOW(),NOW())
                                                ,(NOW(),NOW()) 

所有四个数据库条目是否都具有相同的值,或者 row1 <> row2 是否可能?

请注意,这是一个理论问题,而不是一个work-around问题。
我真的很想知道如何以及为什么。

4

5 回答 5

10

With Postgres now() always returns the timestamp which denotes the beginning of the transaction.

So for your second example all four rows will have the same timestamp value.

If you want to have the "real" timestamp you have to use clock_timestamp().

More details are in the manual:

http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT

于 2011-09-01T13:20:33.157 回答
4

如果您的查询不需要很长时间,那么所有值都相同的变化是相当高的。我不会依赖它。更好的方法是先将值放入变量中,然后多次使用该变量。

于 2011-09-01T13:16:22.803 回答
2

如果你必须让它们都一样,你最好先定义一个 now 变量,然后将所有列设置为那个。

于 2011-09-01T13:10:51.470 回答
2
DECLARE @Timestamp DATETIME
SELECT @Timestamp = getDate()
INSERT INTO table1 (datetime1, datetime2) VALUES (@Timestamp, @Timestamp)

如果这是您想要的,上面将在表中的两个字段中创建相等的值。

如果您使用的数据库支持 NOW(),并且您想要唯一的日期时间值,您的查询将生成它,尽管时间更改会很短。

于 2011-09-01T13:17:09.450 回答
0

Turns out there has already been a question similar to yours, but it was specifically about MySQL.

As follows from Richard's answer, the value returned by NOW() is fixed at the beginning of the statement's execution and never changed till the execution is complete, which is confirmed by documentation. Similarly to PostgreSQL, there's another function in MySQL too that returns the actual timestamp, the one that corresponds to the time of the evaluation the statement's particular part that contains the function, and that function is SYSDATE().

References:

于 2011-09-30T06:08:40.323 回答