例如,可以
SELECT foo
FROM bar
WHERE foo BETWEEN 5 AND 10
选择5和10,否则它们将被排除在范围之外?
例如,可以
SELECT foo
FROM bar
WHERE foo BETWEEN 5 AND 10
选择5和10,否则它们将被排除在范围之外?
当前回答
如果你按了这个,并且真的不想尝试处理在代码中添加一天,那么让DB来做。
myDate >= '20090101 00:00:00' AND myDate < DATEADD(day,1,'20090101 00:00:00')
如果你确实包含了时间部分:确保它指向午夜。否则,你可以简单地省略时间:
myDate >= '20090101' AND myDate < DATEADD(day,1,'20090101')
不用担心。
其他回答
之间(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.
它确实包括界限。
declare @startDate date = cast('15-NOV-2016' as date)
declare @endDate date = cast('30-NOV-2016' as date)
create table #test (c1 date)
insert into #test values(cast('15-NOV-2016' as date))
insert into #test values(cast('20-NOV-2016' as date))
insert into #test values(cast('30-NOV-2016' as date))
select * from #test where c1 between @startDate and @endDate
drop table #test
RESULT c1
2016-11-15
2016-11-20
2016-11-30
declare @r1 int = 10
declare @r2 int = 15
create table #test1 (c1 int)
insert into #test1 values(10)
insert into #test1 values(15)
insert into #test1 values(11)
select * from #test1 where c1 between @r1 and @r2
drop table #test1
RESULT c1
10
11
15
SQL Server 2008的真实例子。
源数据:
ID Start
1 2010-04-30 00:00:01.000
2 2010-04-02 00:00:00.000
3 2010-05-01 00:00:00.000
4 2010-07-31 00:00:00.000
查询:
SELECT
*
FROM
tbl
WHERE
Start BETWEEN '2010-04-01 00:00:00' AND '2010-05-01 00:00:00'
结果:
ID Start
1 2010-04-30 00:00:01.000
2 2010-04-02 00:00:00.000
如果列数据类型为datetime,则可以执行以下操作,从datetime中消除时间,只在日期范围之间进行比较。
where cast(getdate() as date) between cast(loginTime as date) and cast(logoutTime as date)
如果你按了这个,并且真的不想尝试处理在代码中添加一天,那么让DB来做。
myDate >= '20090101 00:00:00' AND myDate < DATEADD(day,1,'20090101 00:00:00')
如果你确实包含了时间部分:确保它指向午夜。否则,你可以简单地省略时间:
myDate >= '20090101' AND myDate < DATEADD(day,1,'20090101')
不用担心。