2011-03-29 72 views
2

我试图获取仅在查询运行当天的05:00:00之前在系统中存在的记录列表。我有这个查询在基本测试中工作,但我想看看是否有比执行SQL连接更好的选项。SQL Server在定义的时间之前获取记录

select * 
    from Payment 
where createTimestamp <= CONVERT(VARCHAR(10), Getdate(), 120) +' '+'17:00:00'; 

这个查询的SQL Server上使用2008年

+0

当天下午5点之前......你是否也只希望自前一天下午5点开始录音? – 2011-03-29 19:21:36

+0

“仅在当天下午5点之前查询运行”是指“在给定日期的下午5点之前的任何日期”(包括前几天的项目)还是意味着“在当天但下午5点之前”? – Thomas 2011-03-29 19:32:53

+0

@ Neil:这是针对每个星期三运行的计划任务。所以我们只需要支付“待付款”状态下的所有付款。所以没有要求查看前一天的时间。我必须寻找“待付”状态。 @Thomas:前者。 – 2011-03-29 19:49:52

回答

4
Select ... 
From Payment 
Where CreateTimeStamp <= DateAdd(hh, 17, DateDiff(d, 0, CURRENT_TIMESTAMP)) 

另一种选择给您使用的是SQL Server 2008中

Select ... 
From Payment 
Where CreateTimeStamp <= DateAdd(hh, 17, Cast(Cast(CURRENT_TIMESTAMP As Date) As DateTime)) 
+0

我尝试了2008年的选择,它的工作。谢谢。 – 2011-03-29 19:52:14

0

这将检索与之间的createTimestamp所有记录上午12点和下午5点。

select * 
    from Payment 
where createTimestamp 
     between dateadd(dd, datediff(dd, 0, getdate()), 0) 
      and dateadd(hh, 17, dateadd(dd, datediff(dd, 0, getdate()), 0)) 

这将检索今天昨天下午5点下午5点之间的createTimestamp的所有记录。

select * 
    from Payment 
where createTimestamp 
     between dateadd(hh, -7, dateadd(dd, datediff(dd, 0, getdate()), 0)) 
      and dateadd(hh, 17, dateadd(dd, datediff(dd, 0, getdate()), 0)) 

为了更有趣的SQL日期检查我的回答GETDATE last month