質問

If I do

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

Will the two fields always be identical in both columns?

Ditto for

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

Will all four database entries have the same value, or is it possible that row1 <> row2?

Note this is a theoretical question rather than a work-around question.
I just really want to know the how and why.

役に立ちましたか?

解決

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

他のヒント

If your query does not take to long, the change that all values are the same is pretty high. I would not rely on it though. A better approach is putting the value in a variable first and than use that variable multiple times.

If you must have them all the same, you would do better defining a now variable first, and setting all of the columns to that.

DECLARE @Timestamp DATETIME
SELECT @Timestamp = getDate()
INSERT INTO table1 (datetime1, datetime2) VALUES (@Timestamp, @Timestamp)

The above will create equal values in both fields in the table, if that is what you want.

If the database you are using supports NOW(), and you want unique date time values, your query will produce it, though the time changes will be short.

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:

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top