The following functions returns the number of years, months and days between two dates. The first returns a table format, and the second returns 1 value at a time
2007-10-02 (first published: 2002-06-20)
15,449 reads
The following functions returns the number of years, months and days between two dates. The first returns a table format, and the second returns 1 value at a time
/* Returns the number of years, months and days between @startdate and @enddate in a table format USAGE: "Select * From dbo.udfElapsedDate('09/11/2001','07/04/2004)" */ CREATE FUNCTION udfElapsedDate ( @startdate SMALLDATETIME, @enddate SMALLDATETIME ) RETURNS @retElapsed TABLE (Years SMALLINT, Months TINYINT, Days TINYINT) AS BEGIN DECLARE @smonth TINYINT, @sday TINYINT, @syear SMALLINT DECLARE @emonth TINYINT, @eday TINYINT, @eyear SMALLINT DECLARE @months TINYINT, @days TINYINT, @years SMALLINT DECLARE @tdate SMALLDATETIME SET @smonth = MONTH(@startdate) SET @sday = DAY(@startdate) SET @syear = YEAR(@startdate) SET @emonth = MONTH(@enddate) SET @eday = DAY(@enddate) SET @eyear = YEAR(@enddate) SET @years = @eyear - @syear SET @months = 0 SET @days = 0 IF (@emonth >= @smonth) SET @months = @emonth - @smonth ELSE BEGIN SET @years = @years - 1 SET @months = @emonth + 12 - @smonth END IF (@eday >= @sday) SET @days = @eday - @sday ELSE BEGIN IF (@months > 0) SET @months = @months - 1 ELSE BEGIN SET @years = @years - 1 SET @months = @months + 11 END SET @tdate = DATEADD(yy,@years,@startdate) SET @tdate = DATEADD(m,@months,@tdate) SET @days = DATEDIFF(d,@tdate,@enddate) END INSERT @retElapsed SELECT @years, @months, @days RETURN END /* Returns the number of years, months and days between @startdate and @enddate but requires 3 calls, 1 for each of Y,M,D USAGE: select dbo.udfElapsedDatePart ('09/11/2001','07/04/2004','D') */ CREATE FUNCTION udfElapsedDatePart ( @startdate SMALLDATETIME, @enddate SMALLDATETIME, @period CHAR(1) ) RETURNS INT AS BEGIN DECLARE @smonth TINYINT, @sday TINYINT, @syear SMALLINT DECLARE @emonth TINYINT, @eday TINYINT, @eyear SMALLINT DECLARE @months TINYINT, @days TINYINT, @years SMALLINT DECLARE @tdate SMALLDATETIME, @ret INT SET @smonth = MONTH(@startdate) SET @sday = DAY(@startdate) SET @syear = YEAR(@startdate) SET @emonth = MONTH(@enddate) SET @eday = DAY(@enddate) SET @eyear = YEAR(@enddate) SET @years = @eyear - @syear SET @months = 0 SET @days = 0 IF (@emonth >= @smonth) SET @months = @emonth - @smonth ELSE BEGIN SET @years = @years - 1 SET @months = @emonth + 12 - @smonth END IF (@eday >= @sday) SET @days = @eday - @sday ELSE BEGIN IF (@months > 0) SET @months = @months - 1 ELSE BEGIN SET @years = @years - 1 SET @months = @months + 11 END SET @tdate = DATEADD(yy,@years,@startdate) SET @tdate = DATEADD(m,@months,@tdate) SET @days = DATEDIFF(d,@tdate,@enddate) END IF @period = 'Y' SET @ret = @years IF @period = 'M' SET @ret = @months IF @period = 'D' SET @ret = @days RETURN @ret END