将Date参数和时间参数添加到单个日期时间

时间:2011-05-09 14:30:26

标签: sql sql-server

我正在修改SQL Server 2008中的存储过程。原始过程有两个日期

@StartDate DATETIME
@EndDate   DATETIME

并将时间部分分别转换为最早和最晚的时间。

我添加了两个额外的参数来接受时间部分。

@StartTime DATETIME
@EndTime   DATETIME

时间部分是可选的。

RDL报告文件为用户在线生成报告。逻辑需要在存储过程中发生。

到目前为止,我所做的并不多,因为我是一名离开我的元素的C#程序员。

IF (@StartTime IS NULL)
    SET @StartDate = fn_SetBeginningTime(@StartDate) -- Sets time portion to earliest value 
ELSE
    -- This is where I don't know how to add the time from @StartTime to the time portion of the datetime value @StartDate
IF (@EndTime IS NULL)
    -- This will do the same as the start time/start date

1 个答案:

答案 0 :(得分:0)

假设:

  1. 最早你的意思是开始日期的00:00:00
  2. 最新消息指截止日期后的第00:00:00(与<=一起使用)
  3. 如果有,这将忽略@*Date参数的时间和@*Time参数的日期。

    declare @StartDate DATETIME = '15 jul 2010'
    declare @EndDate   DATETIME = '15 jul 2010'
    declare @StartTime DATETIME = '06:06:06'
    declare @EndTime   DATETIME = null
    
    --always make @StartDate/@EndDate's time 00:00:00
    SET @StartDate = CAST(@StartDate AS DATE)
    SET @EndDate =   CAST(@EndDate AS DATE)
    
    IF (@StartTime IS NOT NULL)                -- set @StartDate's time to @StartTime
        SET @StartDate += CAST(@StartTime AS TIME)
    
    IF (@EndTime IS NULL)
        SET @EndDate += 1                      --set it to midnight
    ELSE
        SET @EndDate += CAST(@EndTime AS TIME) --set @EndDate's time to @EndTime
    
    select @StartDate, @EndDate
    
    >>> 2010-07-15 06:06:06.000,2010-07-16 00:00:00.000
    

    日期/时间;

    declare @StartDate DATE = '15 jul 2010'
    declare @EndDate   DATE = '15 jul 2010'
    declare @StartTime TIME = null
    declare @EndTime   TIME = '22:22:22'
    
    declare @start datetime = cast(@StartDate as datetime) + coalesce(@StartTime, cast('00:00:00' as time))
    declare @end   datetime = cast(@EndDate   as datetime) + coalesce(@EndTime,   cast('23:59:59' as time))
    
    select @start, @end