【问题标题】:TSQL Parameter for specific timeframes (day previous 4PM to today noon)?特定时间范围的 TSQL 参数(前一天下午 4 点到今天中午)?
【发布时间】:2018-08-17 21:21:40
【问题描述】:

我希望为特定时间范围创建一个 TSQL 参数,例如 MorningTimeFrame 将在昨天从下午 4 点拉到今天中午,而 AfternoonTimeFrame 将在今天中午拉到今天下午 4 点。我该如何设置?我熟悉 Dateadd(day,datediff(day,1,GETDATE()),0) 但不确定如何将其设置为特定时间。

【问题讨论】:

  • 您使用的是什么版本的 SQL Server?

标签: sql-server tsql datetime


【解决方案1】:

您可以根据以下查询获取这些所需的时间范围值

Select Cast(Cast(CAST(dateadd(d,-1,getdate()) AS date) as varchar) + ' 16:00:00' as datetime)AS 'MorningStartTime', Cast(Cast(CAST(getdate() AS date) as varchar) + ' 12:00:00' as datetime)AS 'MorningEndAfterNoonStartTime', Cast(Cast(CAST(getdate() AS date) as varchar) + ' 16:00:00' as datetime)AS 'AfterNoonEndTime'

使用方便

【讨论】:

  • 完美!谢谢!
【解决方案2】:

简单的东西就足够了吗?

declare @Start as DateTime, @End as DateTime;
declare @Timeframe as VarChar(32) = 'MorningTimeframe';

-- Start from midnight today.
declare @Today as DateTime = Cast( GetDate() as Date );

-- Calculate the timeframe.
if @Timeframe = 'MorningTimeframe'
  begin -- Yesterday 4PM through noon today.
  select @Start = DateAdd( hour, -8, @Today ),
    @End = DateAdd( hour, 12, @Today );
  end
else if @Timeframe = 'AfternoonTimeframe'
  begin -- Noon today through 4PM.
  select @Start = DateAdd( hour, 12, @Today ),
    @End = DateAdd( hour, 16, @Today );
  end
else
  begin
  RaIsError( 'Unexpected timeframe: ''%s''', 16, 42, @Timeframe );
  end;

-- Display the results.
select @Today as [Today], @Timeframe as Timeframe, @Start as [Start], @End as [End];

【讨论】:

  • 这不会,因为不能保证他们会在中午运行它,所以它需要查看确切的时间。
  • 请见谅,但您的评论和问题不清楚。您的问题提到了一个参数,例如传递给存储过程 (SP) 的东西,尽管没有引用 SP 或如何使用它。注释是指在中午以外的某个时间运行代码,但代码不假设它运行的时间。当您运行代码时,哪些值不正确?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 1970-01-01
  • 2013-11-27
  • 2015-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多