Using the function DATEDIFF
You get an integer representing the difference between two dates. As the rounding you want is in the minute box, you only need to calculate the difference between the moment 0 and the specified time summed 30 seconds, which will "skip" one minute if it has 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 the zero moment, thus obtaining the rounded minute:
SET @tempo = DATEADD(MINUTE, @diferenca, 0);
To show formatted time use CONVERT
:
PRINT CONVERT(VARCHAR(5), @tempo, 108);
Applying to your examples
03:56:59
showcase 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
showcase 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 (signal integer) of the specified limits of datepart
cross-checked between the specified parameters startdate
and enddate
.
DATEADD
Returns a specified date with the specified number range (signed integer) added to the datepart
specified at that date.
CAST
and CONVERT
Converts an expression from one data type to another.
Adapted from the answer to the question T-SQL datetime rounded to Nearest minute and Nearest hours with using functions of Stack Overflow
Put a Fiddle, it’s gonna be cool!
– Marconi
@Marconi opa, thanks for the suggestion, I put in Fiddle!
– Sorack
@otaciojb to apply in your
query
I need to know what kind of column dataREF
– Sorack
With the command you applied below simplified worked here, Thank you, I have already marked as answer, put as follows: CONVERT(varchar(5), DATEADD(MINUTE, DATEDIFF(MINUTE, 0, DATEADD(SECOND, 30, (CONVERT(NVARCHAR, CONVERT(DATETIME, P.REF/24), 108)))), 0), 108),
– Chefe Druida
Your sql fiddle is giving this error. Please edit it. tested on 09/07/2019
– user12100