UFN_DATESPANISNOMORETHANYEARS

Checks to see that the span between two dates is no more than the specified number of years.

Return

Return Type
bit

Parameters

Parameter Parameter Type Mode Description
@STARTDATE date IN
@ENDDATE date IN
@NUMYEARSALLOWED int IN

Definition

Copy


            CREATE FUNCTION dbo.UFN_DATESPANISNOMORETHANYEARS
                (
                    @STARTDATE date,
                    @ENDDATE date,
                    @NUMYEARSALLOWED int = 1
                )
                RETURNS BIT
            AS 
            BEGIN

                /*
                Swapping the dates will not reliably detect a reversal of start date and end date.  For example,
                if the max diff = 2 years, and the start date is in 2010 and the end date is in 2009, then this
                function with date swapping in place will return 1 (i.e, no problem).  Thus any check for valid dates must also 
                check for start date < end date regardless.  Once that check for start < end is in place, there is no value 
                in swapping the dates inside this function.  If the dates are not swapped, the datediff will be < 0 
                and the function will return ...but so what?  The check for start < end will catch that error, and 
                return a more reliable error message in the bargain.
                - ChrisFal, 10/25/2010
                */

                /*
                if (@STARTDATE > @ENDDATE)
                begin
                    declare @DATESWAP date;
                    set @DATESWAP = @ENDDATE;
                    set @ENDDATE = @STARTDATE;
                    set @STARTDATE = @DATESWAP;
                end
                */

                -- to be inclusive of the end date bump it up 1 day

                set @ENDDATE = DATEADD(D, 1, @ENDDATE);

                --Determine the difference in years 

                declare @YEARDIFF int;
                set @YEARDIFF  = DATEDIFF(YYYY, @STARTDATE, @ENDDATE);

                -- If we are over the difference in years we 

                if (@YEARDIFF > @NUMYEARSALLOWED)
                    return 0;

                declare @NEWSTARTDATE datetime;
                set @NEWSTARTDATE = DATEADD(YYYY, @NUMYEARSALLOWED, @STARTDATE);

                --Handle those always wacky leap years...

                if ((MONTH(@STARTDATE) = 2) AND (DAY(@STARTDATE) = 29))
                    set @NEWSTARTDATE = DATEADD(D, 1, @NEWSTARTDATE)  --This is converted to 02/28 when you add a year but I want it to move to 03/01


                if ((@YEARDIFF = @NUMYEARSALLOWED) AND (DATEDIFF(S, @NEWSTARTDATE, @ENDDATE) > 0))
                    return 0;

                return 1;
            END