Monday, January 5, 2015

time roundup function same as Mround in Excel

Regarding your description, your requirement is a user-defined function which rounds up time basing on a given input, right?



If my understanding on your requirement is right, please see the blow code which can achieve your requirement.



USE testDB
IF OBJECT_ID (N'dbo.dtMround') IS NOT NULL
DROP FUNCTION dbo.dtMround;
GO
CREATE FUNCTION dbo.dtMround(@dt datetime,@roundByMin int)
RETURNS datetime
AS
BEGIN
DECLARE @mod INT;

--the @dt would be rounded up here to the nearest minute, eg: 2014-01-01 10:10:17 -->2014-01-01 10:10:00,2014-01-01 10:10:31-->2014-01-01 10:11:00
SET @dt=DATEADD(mi, DATEDIFF(mi, 0, DATEADD(s, 30, @dt)), 0);

SET @mod=DATEDIFF(MINUTE,CAST(@dt AS DATE),@dt)%@roundByMin;

IF @mod=0
RETURN @dt
IF @mod>=@roundBYMin/2
RETURN DATEADD(MINUTE,@roundByMin,DATEADD(MINUTE,@mod*-1,@dt))

RETURN DATEADD(MINUTE,@mod*-1,@dt)

END;
GO


DECLARE @dt DATETIME = '2015-1-1 10:10:000'
--@dt roundup by 15 minutes
SELECT dbo.dtMround(@dt,15) --output 2015-01-01 10:15:00.000
--@dt roundup by 75 minutes
SELECT dbo.dtMround(@dt,75) --output 2015-01-01 10:10:00.000



If you have any question, feel free to let me know.


Best regards,

Eric Zhang


No comments:

Post a Comment