August 29, 2016 at 6:38 am
sknox (8/25/2016)
The correct answer is "it depends."MOST of the time you'll get two rows as explained in the answer.
HOWEVER, each GETDATE() within each SELECT is evaluated separately. When the separate evaluations cross a 3-millisecond boundary, you'll get 3 rows instead of 2.
Good catch.
August 29, 2016 at 7:04 pm
pstanislav (8/26/2016)
I agree with the comments here - the code as written will produce variable results as the separate GETDATE functions are evaluated. This can be avoided by getting and holding the current time and using that variable instead:DECLARE @CurrDtTime AS DATETIME = GETDATE();
SELECT @CurrDtTime
UNION
SELECT CAST(@CurrDtTime AS DATETIME2)
UNION
SELECT CAST(@CurrDtTime AS DATETIME)
UNION
SELECT CAST(@CurrDtTime AS SMALLDATETIME)
UNION
SELECT CAST(@CurrDtTime AS DATETIME2(7))
+1.
But even then the answer is not certain.
If you happen to run the query on an exact minute it will return 1 record.
Try this:
DECLARE @CurrDtTime AS DATETIME = DATEADD(n, DATEDIFF(n, 0, GETDATE()), 0);
_____________
Code for TallyGenerator
August 30, 2016 at 6:40 am
Notwithstanding the above comments, I think using a static datetime value would have been better to remove ambiguity.
Also there is no mention in the answer of the datatype precedence in the union as all the values would be converted to DATETIME2(7) prior to the union.
Far away is close at hand in the images of elsewhere.
Anon.
September 5, 2016 at 10:28 pm
It's right. I got 3 rows after run this query
September 7, 2016 at 6:35 am
Interesting question, but flawed execution. Thanks.
Need an answer? No, you need a question
My blog at https://sqlkover.com.
MCSE Business Intelligence - Microsoft Data Platform MVP
Viewing 5 posts - 16 through 19 (of 19 total)
You must be logged in to reply to this topic. Login to reply