Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

sql server - Will GETUTCDATE() return the same value if used twice in the same statement?

I have a trigger that automatically sets the CreationDate and ModifiedDate of the given entry to the current UTC time whenever a value is entered. (CreationDate will remain the same thereafter, while ModifiedDate will be updated on each update via another trigger).

I want to make sure that inserted-and-never-updated items will have exactly the same value for CreationDate and ModifiedDate, so I've used a variable like this:

DECLARE @currentTime DATETIME
SELECT @currentTime = GETUTCDATE()
UPDATE dbo.MyTable SET CreationDate = @currentTime, ModifiedDate = @currentTime
    ...

In my imperative-programming mentality, I am assuming this prevents GETUTCDATE() from being called twice, and potentially producing slightly different results. Is this actually necessary? If not, would this be more expensive, less expensive, or exactly the same as the following code?

UPDATE dbo.MyTable SET CreationDate = GETUTCDATE(), ModifiedDate = GETUTCDATE()
    ...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Thanks to the links provided by gbn, I believe this answers my question:

In common with rand() It is evaluated once per column but once evaluated remains the same for all rows. ... look at the ComputeScalar operator properties in the actual execution plan you will see that GetDate() is evaluated twice.

I checked, and it appears that this still happens the same way in SQL Server 2008: GetUtcDate() is evaluated twice in the execution plan. It is not going to produce different results per row, but it is possible that it could produce a different result per column if the timing ended up just right.

Edit

I can actually prove this behavior! Try this:

select GETUTCDATE(), RAND(), RAND(), ...[~3000 RAND()s]..., RAND(), GETUTCDATE()
from [TableOfYourChoice]

In my experiment, I ended up with 2011-05-17 20:47:34.247 in the first column and 2011-05-17 20:47:34.250 in the final column, showing a difference of three milliseconds as a result of the evaluation of all the RAND()s between the first and second calls to GETUTCDATE().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...