SQL Server和/或圆括号优先级了解

时间:2017-06-14 23:51:16

标签: sql-server sql-server-2008

我很久以前写过一个sql查询,当我重新访问该查询时,我对查询的where条件感到困惑。以下是sql应该做什么的简要介绍:sql尝试查找昨天关闭的所有订单或者处于打开状态并且已经打开超过10天的所有订单。

这是sql代码

DECLARE           
@start_date as datetime,
@end_date as datetime

 SET @start_date =  dateadd(dd, datediff(dd,0,getdate())-2, 0)

 SET @end_date =  dateadd(dd, datediff(dd,0,getdate())-1, 0)

Select * from OrdersTable
---- all columns are coming from one table only           
Where 
(
  (Closed Date>=@start_date and Closed Date<@end_date and order_status='Closed' )
  or 
 (order_Status='Open')---this tells us the cases is open                                                                                
 and 
 datediff(ss,OrderStarDate,
   dateadd(dd,datediff(dd,0,getdate()),0))/86400.0 >= 10

现在这种混乱......

在where子句中的'或'条件之后,所有内容都应在下面的一个括号内:

Select * from OrdersTable
 ----all columns are coming from one table only 
Where
(
   (Closed Date>=@start_date and Closed Date<@end_date and order_status='Closed' )
   or (order_Status='Open' ---In above query I mistakenly closed the parantheses here
   and 
  datediff(ss,OrderStarDate,
  dateadd(dd,datediff(dd,0,getdate()),0))/86400.0 >= 10

)---the Parentheses should have been closed here

)----The final parentheses like the above query no change here

所以我尽力解释这个问题。如果有人可以回答:我的第一个查询错误仍然可以作为第二个查询(正确的查询)。我问的原因是当我更正我的sql时,我得到的记录与我运行错误查询时的记录相同....我正在尝试找到一个合理的答案,为什么会发生这种情况。

1 个答案:

答案 0 :(得分:0)

为了更好地理解您的问题:

where子句中,您有括号

1. ( this means you have a group or enclosed condition with a two Contents 
     in or Operand

  2.() and this one is your first condition
     or 
  3.( while this one is your second condition with
     4. (Wrapper DateDiff
       5. ( second DateDiff inside the wrapper
        ) End Second DateDiff
     )End Wrapper

    ) End of second condition

) End here

您的查询将首先关闭1号码,但您的号码为2,这就是搜索首先更改为号码2的原因。 2完成后,它将进入3。

为了简要解释一下,它将首先始终在每个操作数的CloseOpen括号中。