This function is to convert duration in minutes to readable hours and minutes format. i.e 2h30m. It eliminates the hours if the duration is less than one hour, and shows only the hours if the duration in hours with no extra minutes.
CREATE FUNCTION [dbo].[MinutesToDuration]
(
@minutes int
)
RETURNS nvarchar(30)
AS
BEGIN
declare @hours nvarchar(20)
SET @hours =
CASE WHEN @minutes >= 60 THEN
(SELECT CAST((@minutes / 60) AS VARCHAR(2)) + 'h' +
CASE WHEN (@minutes % 60) > 0 THEN
CAST((@minutes % 60) AS VARCHAR(2)) + 'm'
ELSE
''
END)
ELSE
CAST((@minutes % 60) AS VARCHAR(2)) + 'm'
END
return @hours
END
To use this function :
SELECT dbo.MinutesToDuration(23)
Results: 23m
SELECT dbo.MinutesToDuration(120)
Results: 2h
SELECT dbo.MinutesToDuration(147)
Results: 2h27m
Hope this helps!