It seems obvious that if you call GETDATE()
in SQL Server in two execution batches sufficiently far enough apart in time, the return values will be different.
On the other hand, if you call GETDATE()
twice in rapid succession, you are likely to get the same result from both calls because of the finite resolution of the result. But that is not necessarily assured, as the two calls could occur in real time on either side of a multiple of the resolution of the result.
My question is: Is there any scope (in a vague sense) that guarantees that all GETDATE()
calls will return the same value? If you call GETDATE()
multiple times in the same expression? For a single row (but different expressions) within a DML statement? For the entire duration of a single statement? Including any triggers that execute? What if a user procedure is called?
The question comes up when making an expression to yield, for example, the date of first day of the month.
DATEADD(day, 1-DATEPART(day, GETDATE()), GETDATE())
would appear to be the way to do this, but that only works if you are 100% certain that both GETDATE
calls return the same value, even if you run the code right across the boundary between the last day of one month and the first of the next. If one of the GETDATE
calls could return 00:00:00.000 time of the first of the new month but the other one return one unit of resolution before that you would get undesired results (the second of the month that just ended, or the last day of the month that just ended, depending on which GETDATE
call returned the smaller result.
You could dodge the problem to some extent by setting a variable to the result of GETDATE
before executing the DML statement, and referring to that variable rather than calling GETDATE
within the DML statement, but this is only available in the lexical context; procedures you call and triggers you invoke will still get their own GETDATE
values.
The same question applies to all the other date-getter functions like SYSDATETIME
etc, both among multiple calls to each but also among calls to several of these functions.