0

我的查询是

Select * from Orders 
where ordersdate Between '2013-10-10 00:00:00.00' and '2013-10-10 23:59:59.997'

我需要每天运行这个查询,它应该是前一天的日期。所以如何以上述格式生成日期是我正在努力解决的问题。

4

4 回答 4

2
Select * 
from Orders
where ordersdate >= cast(dateadd(d, -1, getdate()) as date)
and ordersdate < cast(getdate() as date)

time您可以使用>=昨天的日期和<今天,而不是附加的。

于 2013-10-11T08:44:44.567 回答
0
DECLARE @StartDate DATETIME, @EndDate DATETIME

/* set the end date to midnight of the previous day */
SET @EndDate = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 121), 121) 
/* set the start date to 1 day previously (thereby getting midnight to midnight) */
SET @StartDate = DATEADD(day, -1, @EndDate)

/* you could use between, but orders placed at midnight might be counted twice (on subsequent day reports) */
Select * from Orders where ordersdate Between @StartDate AND @EndDate

/* or you could use >= and < to guarantee that a order placed at midnight will only be counted once */
Select * from Orders where ordersdate >= @StartDate AND ordersdate < @EndDate
于 2013-10-11T09:12:37.077 回答
0
select * 
from orders 
where datediff(d, ordersdate, getdate()) = 1

/edit/ 根据 Jason Musgrove 的评论 - 这样的查询很容易编写和理解,但依赖于行数可能会变得非常低效。

于 2013-10-11T09:01:14.977 回答
-1

采用稍微不同的方法(但可能不如 Arvo 的答案),并且有更快的方法来执行演员表

select * 
from orders 
where cast(ordersdate as varchar(11))  = cast( dateadd(dd,-1,getdate()) as varchar(11) )
于 2013-10-11T09:04:52.080 回答