例如,可以

SELECT foo
FROM bar
WHERE foo BETWEEN 5 AND 10

选择5和10,否则它们将被排除在范围之外?


当前回答

BETWEEN操作符是包含的。

来自图书在线:

的值,则BETWEEN返回TRUE Test_expression大于或 等于begin_expression的值 小于或等于的值 end_expression。

DateTime警告

注意:使用DateTimes你必须小心;如果只给出一个日期,则以当天午夜为准;为了避免在结束日期中错过时间,或者在午夜重复多个范围内捕获第二天的数据,您的结束日期应该在您的日期之后的第二天的午夜前3毫秒。3毫秒,因为如果小于这个值,则该值将四舍五入到第二天的午夜。

例如,要在2016年6月内获得所有值,您需要运行:

where myDateTime在'20160601'和DATEADD之间(毫秒,-3,'20160701')

i.e.

where myDateTime在'20160601 00:00:00.000'和'20160630 23:59:59.997'之间

日期,日期

从日期中减去3毫秒将使您容易从3毫秒窗口中遗漏行。正确的解决方案也是最简单的:

where myDateTime >= '20160601' AND myDateTime < '20160701'

其他回答

如果你按了这个,并且真的不想尝试处理在代码中添加一天,那么让DB来做。

myDate >= '20090101 00:00:00' AND myDate < DATEADD(day,1,'20090101 00:00:00')

如果你确实包含了时间部分:确保它指向午夜。否则,你可以简单地省略时间:

myDate >= '20090101' AND myDate < DATEADD(day,1,'20090101')

不用担心。

如果列数据类型为datetime,则可以执行以下操作,从datetime中消除时间,只在日期范围之间进行比较。

where cast(getdate() as date) between cast(loginTime as date) and cast(logoutTime as date)

BETWEEN操作符是包含的。

来自图书在线:

的值,则BETWEEN返回TRUE Test_expression大于或 等于begin_expression的值 小于或等于的值 end_expression。

DateTime警告

注意:使用DateTimes你必须小心;如果只给出一个日期,则以当天午夜为准;为了避免在结束日期中错过时间,或者在午夜重复多个范围内捕获第二天的数据,您的结束日期应该在您的日期之后的第二天的午夜前3毫秒。3毫秒,因为如果小于这个值,则该值将四舍五入到第二天的午夜。

例如,要在2016年6月内获得所有值,您需要运行:

where myDateTime在'20160601'和DATEADD之间(毫秒,-3,'20160701')

i.e.

where myDateTime在'20160601 00:00:00.000'和'20160630 23:59:59.997'之间

日期,日期

从日期中减去3毫秒将使您容易从3毫秒窗口中遗漏行。正确的解决方案也是最简单的:

where myDateTime >= '20160601' AND myDateTime < '20160701'

我一直用这个:

WHERE myDate BETWEEN startDate AND (endDate+1)

之间(transact - sql) 指定要测试的(n)(包括)范围。

test_expression [ NOT ] BETWEEN begin_expression AND end_expression

Arguments test_expression Is the expression to test for in the range defined by begin_expression and end_expression. test_expression must be the same data type as both begin_expression and end_expression. NOT Specifies that the result of the predicate be negated. begin_expression Is any valid expression. begin_expression must be the same data type as both test_expression and end_expression. end_expression Is any valid expression. end_expression must be the same data type as both test_expression and begin_expression. AND Acts as a placeholder that indicates test_expression should be within the range indicated by begin_expression and end_expression. Remarks To specify an exclusive range, use the greater than (>) and less than operators (<). If any input to the BETWEEN or NOT BETWEEN predicate is NULL, the result is UNKNOWN. Result Value BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression. NOT BETWEEN returns TRUE if the value of test_expression is less than the value of begin_expression or greater than the value of end_expression.