首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Server在where子句中生成日期字段数据

Server在where子句中生成日期字段数据
EN

Stack Overflow用户
提问于 2013-10-11 08:42:42
回答 4查看 96关注 0票数 0

我的疑问是

代码语言:javascript
复制
Select * from Orders 
where ordersdate Between '2013-10-10 00:00:00.00' and '2013-10-10 23:59:59.997'

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-10-11 09:12:37

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2013-10-11 08:44:44

代码语言:javascript
复制
Select * 
from Orders
where ordersdate >= cast(dateadd(d, -1, getdate()) as date)
and ordersdate < cast(getdate() as date)

替代附加的time,您可以使用>=昨天的日期和今天的<

票数 2
EN

Stack Overflow用户

发布于 2013-10-11 09:01:14

代码语言:javascript
复制
select * 
from orders 
where datediff(d, ordersdate, getdate()) = 1

/编辑/按Jason注释--这样的查询很容易编写和理解,但是依赖于行数可能会变得非常无效。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19313846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档