两个日期之间的记录在凌晨04:00而不是00:00变化

时间:2017-04-20 06:11:40

标签: sql sql-server

我想在今天上午11点到明天上午4点之间获取订单记录。

我已尝试过以下代码和start_date结果2017-04-20 11:00:00.000并结束日期2017-04-21 04:00:00.000

但问题是当时钟到达(午夜)上午12点时,start_date结果2017-04-21 11:00:00.000和结束日期2017-04-22 04:00:00.000开始日期和结束日期应具有相同的上述值。

如何解决此问题

查询

DECLARE @start_date datetime = CONVERT(datetime, CONVERT(char(9), CURRENT_TIMESTAMP, 112) + '11:00');
DECLARE @end_date datetime = DATEADD(HOUR, 17, @start_date)
SELECT * from [dbo].[Orders] where [OrderDate] between  @start_date and @end_date

1 个答案:

答案 0 :(得分:1)

只需检查当前日期是否在凌晨4点之前,在这种情况下减去一天。

DECLARE @from datetime 
set @from = getdate();
if (DATEPART(HOUR, @from) < 4) set @from = dateadd(day, -1, @from);

DECLARE @start_date datetime = CONVERT(datetime, CONVERT(char(9), @from, 112) + '11:00');
DECLARE @end_date datetime =     

SELECT * from [dbo].[Orders] where [OrderDate] between  @start_date and @end_date

测试:

DECLARE @from datetime 
--set @from = getdate();
set @from = '2017-04-21 02:00'  -- We test a value instead of using the current datetime
if (DATEPART(HOUR, @from) < 4) set @from = dateadd(day, -1, @from);

DECLARE @start_date datetime = CONVERT(datetime, CONVERT(char(9), @from, 112) + '11:00');
DECLARE @end_date datetime = DATEADD(HOUR, 17, @start_date)

SELECT @start_date, @end_date   -- Test result

SELECT * from [dbo].[Orders] where [OrderDate] between  @start_date and @end_date

使用2017-04-21 02:00进行测试,返回:2017-04-20 11:00和2017-04-21 04:00