Funkcja – różnica dat

 
ALTER  FUNCTION test1
( @date1 datetime, @date2 datetime )

RETURNS int
AS
BEGIN
   DECLARE @now datetime = getdate();
   DECLARE @yearDiff int;
   DECLARE @date3 datetime;
   set @date3 = CAST(CONVERT(VARCHAR, year(@date1)) + '-' + CONVERT(VARCHAR, month(@now)) + '-' + CONVERT(VARCHAR, day(@now)) AS DATETIME) ;
  
 set @yearDiff = DATEDIFF(year, @date1, @date2);
   IF DATEDIFF(day, @date1, @date3) < 0
      SET @yearDiff =  @yearDiff -1
   RETURN @yearDiff;

END;

 
--select  [dbo].[test1](convert(datetime,'20150114'),getdate())