我正在尝试在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'
答案 0 :(得分:5)
BETWEEN谓词要求 lower 值为第一个值,更高值为秒,否则你什么也得不到。
答案 1 :(得分:2)
要添加@ RBarryYoung的答案,我还建议在您的条件周围添加括号。这使得它明确,你想要的结果/如何应用条件。
即
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')
这是你现在拥有的第二个,而你可能意味着第一个。
阅读Operator Precedence - 这会告诉您执行各种运算符的顺序。在这种情况下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')
答案 2 :(得分: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'