2

我已经声明了一个值为 23:59:59 的时间变量。所以,我需要把它四舍五入到 24:00。你有什么想法吗?

declare @t1 time = '23:59:59'

这仅在 select 语句中是必需的。我知道时间不能插入为 24:00。

http://msdn.microsoft.com/en-us/library/bb677243(v=sql.105).aspx

4

1 回答 1

0

怎么样:

--setup
    declare @t1 time = '23:59:59'
    --declare @t1 time = '00:59:59'
    --declare @t1 time = '00:59:29'
    --declare @t1 time = '00:00:00'

--solution for rounding to nearest hour
    declare @temp1 int = datepart(minute, @t1) / 30
    set @temp1 = (DATEPART(hour, @t1) % 24) + @temp1
    select @t1, cast(@temp1 as nvarchar(2)) + ':00' --not too worried about rpading hours since 1:00 makes sense

--solution for rounding to nearest minute
    declare @ss int = datepart(second, @t1)/30
    , @mm int = datepart(minute, @t1)
    , @hh int = datepart(hour, @t1)
    , @oo nchar(2) = N'00' --used for padding

    set @hh = (@hh + (@mm / 30) * @ss) % 24
    set @mm = (@mm + @ss) % 60

    select @t1
    , substring(@oo + cast(@hh as nvarchar(2)), case when @hh > 9 then 3 when @hh = 0 then 1 else 2 end, 2) --hours rpaded 
     + N':' 
     + substring(@oo + cast(@mm as nvarchar(2)), case when @mm > 9 then 3 when @mm = 0 then 1 else 2 end, 2) --minutes rpaded
于 2012-10-18T21:14:49.653 回答