Showing posts with label MS SQL Server Scalar Valued Function for Difference Between Two Dates. Show all posts
Showing posts with label MS SQL Server Scalar Valued Function for Difference Between Two Dates. Show all posts

Thursday, 5 January 2017

MS SQL Server Scalar Valued Function for Difference Between Two Dates

-- =============================================
-- Author: <Author,,Kapil Dev Mehra>
-- Create date: <Create Date, ,30/12/2016>
-- Description: <Description, ,Get difference between two dates>
-- =============================================
CREATE FUNCTION [dbo].[funGetDiffDates]
(
@NewDate nvarchar(10),
@OldDate nvarchar(10)
)
RETURNS nvarchar(50)
AS
BEGIN
DECLARE @Diff_Day int, @Diff_Month int, @Diff_Year int
DECLARE @OldDate_Day int, @OldDate_Month int, @OldDate_Year int
DECLARE @NewDate_Day int, @NewDate_Month int, @NewDate_Year int
SELECT @OldDate_Day = SUBSTRING(@OldDate,1,2), @OldDate_Month = SUBSTRING(@OldDate,4,2), @OldDate_Year = SUBSTRING(@OldDate,7,4)
SELECT @NewDate_Day = SUBSTRING(@NewDate,1,2), @NewDate_Month = SUBSTRING(@NewDate,4,2), @NewDate_Year = SUBSTRING(@NewDate,7,4)

IF @OldDate_Day > @NewDate_Day
BEGIN
SET @NewDate_Month = @NewDate_Month - 1
SET @NewDate_Day = @NewDate_Day + 30

END
SET @Diff_Day = @NewDate_Day - @OldDate_Day

IF @OldDate_Month > @NewDate_Month
BEGIN
SET @NewDate_Year = @NewDate_Year - 1
SET @NewDate_Month = @NewDate_Month + 12
END
SET @Diff_Month = @NewDate_Month - @OldDate_Month
SET @Diff_Year = @NewDate_Year - @OldDate_Year

DECLARE @Return_Year nvarchar(15), @Return_Month nvarchar(15), @Return_Day nvarchar(15)
IF @Diff_Year > 1
SET @Return_Year = CONVERT(nvarchar, @Diff_Year) + ' Years, '
ELSE
SET @Return_Year = CONVERT(nvarchar, @Diff_Year) + ' Year, '

IF @Diff_Month > 1
SET @Return_Month = CONVERT(nvarchar, @Diff_Month) + ' Months, '
ELSE
SET @Return_Month = CONVERT(nvarchar, @Diff_Month) + ' Month, '

IF @Diff_Day > 1
SET @Return_Day = CONVERT(nvarchar, @Diff_Day) + ' Days'
ELSE
SET @Return_Day = CONVERT(nvarchar, @Diff_Day) + ' Day'

RETURN @Return_Year + @Return_Month + @Return_Day
END


#how to difference between two dates in sql
#how to calculate age by date of birth
#how to get age from date of birth in sql