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)
	-- 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)
            (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


Call the TimeDiff Function

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

The Output

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

As you found this post useful...

Share this post on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?