简体   繁体   English

SQL Server:是否不遵循操作顺序?

[英]SQL Server : order of operations not being followed?

[Running SQL Server 2008 SP3] [运行SQL Server 2008 SP3]

I have a query which results in the overflow of a smalldatetime type. 我有一个查询,导致smalldatetime类型的溢出。 However, this should (in theory) never happen, due to the way I have the query structured - the logic should cause the truth value to be known long before the DATEADD() is executed which causes the overflow. 但是,由于我构造查询的方式,从理论上讲永远不会发生-逻辑应该在执行DATEADD()之前很早就知道真值,这会导致溢出。

Here is the relevant part of the WHERE clause: 这是WHERE子句的相关部分:

TimeIn >= '1/8/1950' AND TimeIn < '1/9/1950' AND
DATEADD(week, DATEDIFF(week, '1/8/1950', '9/14/2014'), TimeIn) >= '9/14/2014'

This works great - except when TimeIn (a smalldatetime ) is >= 10/1/2014, then it will overflow the smalldatetime space. 这很好用-除非TimeIn( smalldatetime )> = 10/1/2014,否则它将溢出smalldatetime空间。 But why does DATEADD() even get executed? 但是,为什么DATEADD()甚至被执行? if the date is 10/1/14, it should never be executed... but it is. 如果日期是14年10月1日,它应该永远不会被执行...但它是。

The portions of a WHERE criteria aren't executed in a defined order that prevents your DATEADD() from executing, that's just not how SQL Server works. WHERE条件的部分未按定义的顺序执行,从而阻止了DATEADD()的执行,而这并不是SQL Server的工作方式。

I don't actually see an error when I run your query with the problematic date hard coded, but one way around this would be to use a CASE expression: 使用有问题的日期硬编码运行查询时,我实际上看不到任何错误,但是解决此问题的一种方法是使用CASE表达式:

TimeIn >= '1/8/1950' AND TimeIn < '1/9/1950' 
AND CASE WHEN TimeIn >= '1950-01-08' AND TimeIn < '1950-01-09' 
         THEN DATEADD(week, DATEDIFF(week, '1/8/1950', '9/14/2014'), TimeIn) 
    END >= '2014-09-14'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM