Using the DATEDIFF
function you get an integer representing the difference between two dates. Since the rounding you want is in minutes, you only need to calculate the difference between the 0 and the specified time plus 30 seconds, which will "jump" one minute if you have already passed more than 30 seconds of the minute in question :
DECLARE @diferenca INT = DATEDIFF(MINUTE, 0, DATEADD(SECOND, 30, @tempo));
After this it is necessary to add the result obtained to moment zero, thus obtaining the minute rounded:
SET @tempo = DATEADD(MINUTE, @diferenca, 0);
To show the formatted time use CONVERT
:
PRINT CONVERT(VARCHAR(5), @tempo, 108);
Applying to your examples
03:56:59
shows 03:57
:
DECLARE @tempo TIME = '03:56:59';
DECLARE @diferenca INT = DATEDIFF(MINUTE, 0, DATEADD(SECOND, 30, @tempo));
SET @tempo = DATEADD(MINUTE, @diferenca, 0);
PRINT CONVERT(VARCHAR(5), @tempo, 108);
00:43:12
shows 00:43
:
DECLARE @tempo TIME = '00:43:12';
DECLARE @diferenca INT = DATEDIFF(MINUTE, 0, DATEADD(SECOND, 30, @tempo));
SET @tempo = DATEADD(MINUTE, @diferenca, 0);
PRINT CONVERT(VARCHAR(5), @tempo, 108);
Simplifying:
SELECT CONVERT(varchar(5), DATEADD(MINUTE, DATEDIFF(MINUTE, 0, DATEADD(SECOND, 30, '03:56:59')), 0), 108),
CONVERT(varchar(5), DATEADD(MINUTE, DATEDIFF(MINUTE, 0, DATEADD(SECOND, 30, '00:43:12')), 0), 108)
Example in SQL Fiddler
DATEDIFF
Returns the count (signed integer) of the specified limits of datepart
crossed between the specified parameters startdate
and enddate
.
DATEADD
Returns a specified date with the specified number range (signed integer) added to the specified%% of that date.
datepart
and CAST
Converts an expression from one data type to another.
Adapted from the answer to the question T-SQL datetime rounded to nearest minute and using hours of Stack Overflow