The impetus behind this function is that lately I’ve been asked by couple of fellow developers about a way to find out difference between two datetime values in hh:mm:ss format.
The function below will give you time difference between two datetime values in hh:mm:ss format.Regardless of order in which you give dates it calculates the difference between them and give you result in hh:mm:ss format
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA=’dbo’ AND ROUTINE_NAME=’GetTimeDiff’)
DROP FUNCTION GetTimeDiff
GO
CREATE FUNCTION GetTimeDiff
(@Start datetime,
@End datetime)
RETURNS varchar(15)
AS
BEGIN
DECLARE @DateDiff datetime,@TimeDiff varchar(15)
SELECT @DateDiff=@Start,
@Start=CASE WHEN @End<@Start THEN @End ELSE @Start END,