我需要一个向上舍入到最接近的x分钟的函数。我找到了下面的那个,但它向上或向下舍入到最接近的x分钟。根据另一个值,我要么需要将其四舍五入到最近的半小时或小时。
CREATE FUNCTION [dbo].[RoundTime] (@Time DATETIME, @RoundToMin INT)
RETURNS DATETIME
AS
BEGIN
RETURN ROUND(CAST(CAST(CONVERT(VARCHAR,@Time,121) AS DATETIME) AS FLOAT) * (1440/@RoundToMin),0)/(1440/@RoundToMin)
END
GO
答案 0 :(得分:1)
这会将您的功能更改为四舍五入到任意分钟。
CREATE FUNCTION [dbo].[RoundUpTime] (@Time DATETIME, @RoundToMin INT)
RETURNS DATETIME
AS
BEGIN
return dateadd(mi, - datepart(mi, @time) + (datepart(mi, @time) + @roundToMin - 1) / @roundToMin * @roundToMin, @Time)
END
GO
注意我将名称更改为RoundUpTime。警告,它仅适用于MINUTE部分,并忽略秒和毫秒。
select dbo.RoundUpTime('20121212 12:30:00.003', 30)
--
2012-12-12 12:30
答案 1 :(得分:0)
将ROUND更改为CEILING并从ROUND中删除“,0”:
CREATE FUNCTION [dbo].[RoundTime] (@Time DATETIME, @RoundToMin INT)
RETURNS DATETIME
AS
BEGIN
RETURN CEILING(CAST(CAST(CONVERT(VARCHAR,@Time,121) AS DATETIME) AS FLOAT) * (1440/@RoundToMin))/(1440/@RoundToMin)
END
GO