I have a SELECT
statement that uses GETDATE()
for two different column values. I'm wondering if by the nature of things those two separate function calls in the same SELECT
will return identical values every time?
No they aren't guaranteed to return identical values every time. Each individual reference to GetDate()
is a runtime constant and will keep its value throughout the query...
SELECT GETDATE()
FROM large_table
will return the same value in all rows regardless of how long the query takes to run.
But there is no guarantee that different references will have the same value.
You can see this as below
SET NOCOUNT ON;
DECLARE @T TABLE
(
rownum INT IDENTITY(1,1) PRIMARY KEY,
d1 DATETIME,
d2 DATETIME
)
WHILE (5 > (SELECT COUNT(*) FROM @T WHERE d1 <> d2))
BEGIN
DELETE FROM @T WHERE d1 = d2
INSERT INTO @T
SELECT GETDATE(),GETDATE()
END
SELECT * FROM @T
Example Results
rownum d1 d2
----------- ----------------------- -----------------------
22381 2011-05-18 12:24:14.433 2011-05-18 12:24:14.437
30912 2011-05-18 12:24:15.420 2011-05-18 12:24:15.423
43234 2011-05-18 12:24:16.717 2011-05-18 12:24:16.720
113360 2011-05-18 12:24:24.210 2011-05-18 12:24:24.213
147855 2011-05-18 12:24:27.817 2011-05-18 12:24:27.820
Sorry to say it, but I just came up with a test to show that it will not always return the same value. It actually does get evaluated twice, and if the system clock happens to turn over during the time between those two evaluations, you could get slightly different times out of the two calls.
However, the others are right in saying that it won't be evaluated once per row: only once per column.
See Will GETUTCDATE() return the same value if used twice in the same statement?
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