2014-08-19

TSQL - User defined function that turns a YYYYMM integer, to an actual date type

This will return the date using the first day of the given month.


/*

       -- Execution
       select dbo.getPeriodDate( 201101 );


       -- Bad execution
       select dbo.getPeriodDate( '1/31/2012' );
       select dbo.getPeriodDate( cast('1/31/2012' as date) );



*/
ALTER function [dbo].[getPeriodDate](
       @PeriodID int
)
returns date
as
begin

       return(
              CAST(
                     cast( cast( @PeriodID % 100 as tinyint ) as varchar(2) )
                     + '/1/'
                     +  CAST( cast( @PeriodID / 100 as int ) as varchar(4) )
                     as date
              )
       );

end
;


No comments:

Post a Comment