0

我正在尝试在 SQL Server 的同一 SQL 语句中使用 Between 和 OR 子句,每次我得到空结果时,有人知道吗?我原来的 SQL 是这样形成的:

SELECT * 
FROM opportunity AS oppt
WHERE oppt.Location='O/S' 
   OR oppt.Location='Overseas' 
  AND oppt.OPEN_DATE BETWEEN '2014-01-01 00:00:00.000' 
                         AND '2010-01-01 00:00:00.000'
4

3 回答 3

5

BETWEEN 谓词要求较低的值在前,较高的值在后,否则您将一无所获。

于 2012-12-10T13:49:58.053 回答
2

要添加到@RBarryYoung 的答案,我还建议在您的条件周围加上括号。这使得它明确,你打算成为结果/条件应该如何应用。

IE

WHERE (oppt.Location='O/S' 
   OR oppt.Location='Overseas')
  AND oppt.OPEN_DATE BETWEEN '2014-01-01 00:00:00.000' 
                         AND '2010-01-01 00:00:00.000'

不同于:

WHERE oppt.Location='O/S' 
   OR (oppt.Location='Overseas'
  AND oppt.OPEN_DATE BETWEEN '2014-01-01 00:00:00.000' 
                         AND '2010-01-01 00:00:00.000')

这是您目前拥有的上述第二个,而您可能是指第一个。

阅读运算符优先级- 这会告诉您执行各种运算符的顺序。在这种情况下AND,应用在之前OR。但是,适当地使用括号对您的条件进行分组有助于消除具有意外后果的风险运算符优先级。

我怀疑在您的情况下,您想要上面的第一个示例,实际上您可以将其合理化为:

WHERE oppt.Location IN ('O/S', 'Overseas')
      AND oppt.OPEN_DATE BETWEEN '2010-01-01 00:00:00.000' 
                             AND '2014-01-01 00:00:00.000')
于 2012-12-10T13:59:15.390 回答
0

尝试在语句之间使用 () 进行查询和更正日期(先低后高),

在您的情况下,它将是:

SELECT * 
FROM opportunity AS oppt
WHERE (oppt.Location='O/S' OR oppt.Location='Overseas')
    AND oppt.OPEN_DATE BETWEEN '2010-01-01' AND '2014-01-01'
于 2012-12-10T13:51:22.823 回答