Skip to content

Instantly share code, notes, and snippets.

@mubaidr
Created April 27, 2021 03:21
Show Gist options
  • Save mubaidr/e7cac8074c982ce8e3e5984e438a2c54 to your computer and use it in GitHub Desktop.
Save mubaidr/e7cac8074c982ce8e3e5984e438a2c54 to your computer and use it in GitHub Desktop.
CREATE FUNCTION get_Exact_Date_diff(@date SMALLDATETIME,@date2 SMALLDATETIME)
returns VARCHAR(50)
AS
BEGIN
DECLARE @date3 SMALLDATETIME
DECLARE @month INT,@year INT,@day INT
IF @date>@date2
BEGIN
SET @date3=@date2
SET @date2=@date
SET @date=@date3
END
SELECT @month=datediff (MONTH,@date,@date2)
IF dateadd(month,@month,@date) >@date2
BEGIN
SET @month=@month-1
END
SET @day=DATEDIFF(day,dateadd(month,@month,@date),@date2)
SET @year=@month/12
SET @month=@month % 12
RETURN (CASE WHEN @year=0 THEN '' WHEN @year=1 THEN CONVERT(VARCHAR(50),@year ) + ' year ' WHEN @year>1 THEN CONVERT(VARCHAR(50),@year ) + ' years ' END)
+ (CASE WHEN @month=0 THEN '' WHEN @month=1 THEN CONVERT(VARCHAR(50),@month ) + ' month ' WHEN @month>1 THEN CONVERT(VARCHAR(50),@month ) + ' months ' END)
+ (CASE WHEN @day=0 THEN '' WHEN @day=1 THEN CONVERT(VARCHAR(50),@day ) + ' day ' WHEN @day>1 THEN CONVERT(VARCHAR(50),@day ) + ' days ' END)
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment