2014-08-19

TSQL - User defined function that calculates the difference, in months, of two dates represented by integers using the format YYYYMM

/*

       -- Execution
       select dbo.getPeriodDiff( 201012, 201103 );
       select dbo.getPeriodDiff( 201103, 201012 );

      
*/
ALTER function [dbo].[getPeriodDiff]
(
       @PeriodID1 as int
       , @PeriodID2 as int
)
returns int
as
begin


       -- Get Date
       declare @PeriodDate1 date;
              set @PeriodDate1 = dbo.getPeriodDate( @PeriodID1 );
       declare @PeriodDate2 date;
              set @PeriodDate2 = dbo.getPeriodDate( @PeriodID2 );
      
       -- Return
       return
       (
              datediff( m, @PeriodDate1, @PeriodDate2 )
       );
end;



No comments:

Post a Comment