[英]Wrong result comparing GETDATE() to stored GETDATE() in SQL Server
I would expect the result to always be 1: 我希望结果总是1:
DECLARE @x datetime2
SELECT @x=GETDATE()
SELECT CASE WHEN @x>GETDATE() THEN 0 ELSE 1 END
But it is sometimes 1 and sometimes 0. How is that possible? 但它有时是1,有时是0.这怎么可能?
It takes time for code to execute. 代码执行需要时间。 Sometimes a tick happens in between lines two and three, and sometimes (usually) not. 有时在第二和第三行之间发生嘀嗒,有时(通常)没有。 In the latter case (no tick), @x
is still equal to (not greater than) the GETDATE()
value in the third line and you end up with 0
. 在后一种情况(无蜱), @x
仍然等于(不大于) GETDATE()
在第三行中值和你结束了0
。 What surprised me at first is you ever see 1
. 一开始让我感到惊讶的是你曾经看到过1
。 When a tick does happen, @x
should now be less than the new GETDATE()
value in line 3 and you'd still see 0
. 当勾选确实发生时,@ @x
现在应该小于第3行中的新GETDATE()
值,你仍然会看到0
。
But it makes more sense when you run this code: 但是在运行此代码时更有意义:
DECLARE @x datetime2
SELECT @x=GETDATE()
SELECT @x, GETDATE(), CASE WHEN @x>GETDATE() THEN 0 ELSE 1 END
Now we can see what's going on better. 现在我们可以看到更好的情况。 Here's a sample result on my machine: 这是我机器上的示例结果:
2018-01-19 23:32:21.3833333 | 2018-01-19 23:32:21.383 | 1
Ahhh... @x
is a datetime2
with more precision than the older datetime
used by GETDATE()
. 啊...... @x
是一个datetime2
,其精度高于GETDATE()
使用的旧datetime
。 And you can see in the documentation for GETDATE() that it does return a datetime
rather than datetime2
. 您可以在GETDATE()的文档中看到它确实返回了datetime
而不是datetime2
。 So we have some rounding error going on between the two values. 所以我们在两个值之间发生了一些舍入误差。
For the 0
values, I ran the altered code 30 or 40 times (hitting F5 for refresh), and ALL of the 0
's I saw looked like this: 对于0
值,我运行了改变的代码30或40次(按F5刷新),我看到的所有 0
都是这样的:
2018-01-19 23:36:29.0366667 | 2018-01-19 23:36:29.037 | 0
Where the last digit in the second column was a 7 and the first column had repeating 6's with a rounded 7 at the end. 第二列中的最后一位数字为7,第一列重复6位,末尾为圆形7。
One thing still confuses me. 有一件事让我感到困惑。 The GETDATE()
function returns a datetime
value, but somehow it assigns datetime2
precision to @x
. GETDATE()
函数返回一个datetime
值,但不知何故它将datetime2
精度分配给@x
。 I'd expect to just see extra zeros that always match the original GETDATE()
result. 我希望看到额外的零,它始终与原始的GETDATE()
结果相匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.