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()
...
The GETUTCDATE() function returns the current database system UTC date and time, in a 'YYYY-MM-DD hh:mm:ss.
The difference between GETDATE() and GETUTCDATE() is in timezone, the GETDATE() function returns the current date and time in the local timezone, the timezone where your database server is running, but GETUTCDATE() return the current time and date in UTC (Universal Time Coordinate) or GMT timezone.
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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With