SQL Server Function to find differences between two times

Are you looking for the function to find the differences between to times in SQL server like TIMESTAMPDIFF in My SQL?

Here is the solution for SQL Server 2008 and above.

Function to find Time Differences in SQL Server

-- =============================================
-- Author:		Jignesh Darji
-- Create date: 5 May 2019
-- Description:	SQL Server Function to find differences between two times(TIMESTAMPDIFF)
-- =============================================
CREATE FUNCTION [dbo].[TimeDiff] 
(
	-- Add the parameters for the function here
	@startTime Time,
	@endTime Time
)
RETURNS varchar(10)
AS
BEGIN
	-- Declare the return variable here
	Declare @totalHours varchar(10);
	Declare @hours varchar(2);
	Declare @minutes varchar(2);

	-- Add the T-SQL statements to compute the return value here
	SELECT  @hours=DATEDIFF(MINUTE, StartTime, EndTime)/60,@minutes= DATEDIFF(MINUTE, StartTime, EndTime)- 60*(DATEDIFF(MINUTE, StartTime, EndTime)/60)
	FROM    (VALUES 
            (CAST(@startTime AS TIME), CAST(@endTime AS TIME))
        ) t (StartTime, EndTime);

	SELECT @totalHours=(RIGHT('00'+ISNULL(@hours,''),2) + ':' + RIGHT('00'+ISNULL(@minutes,''),2));
	-- Return the result of the function
	RETURN @totalHours

END

Call the TimeDiff Function

SELECT [TimeDiff] ('11:00','21:26')

The Output

SQL Server Function to find differences between two times