:SetVar Function "AUX:CompareDate.YMD"
:r $(DropFunctionScript_AUX)
create function [$(Function)]( @Date_1 datetime2,
                               @Year_2 int, @Month_2 int=null, @Day_2 int=null )
returns int
BEGIN
/*==================================================================================================
# SQLAUX scripting library | Author: Sergei Y.Kitáev
----------------------------------------------------------------------------------------------------
#
# DATE COMPARISON, WITH ROUNDING TO “YMD” (VIA TRUNCATION OF TIME PARTS):
#
# Comparison result
# :   -1 —— 1st YMD is lesser than 2nd YMD;
# :    1 —— 1st YMD is greater than 2nd YMD;
# :    0 —— 1st YMD is equal to 2nd YMD;
# : null —— correlation is undetermined (null arg(s) or incorrect YMD2)
#
# === Usage: ===
# dbo.[AUX:CompareDate.YMD]( <Date-1>, <Year-2>, <Month-2>, <Day-2> )
# dbo.[AUX:CompareDate.YMD]( <Date-1>, <Year-2>, <Month-2>, null )
# dbo.[AUX:CompareDate.YMD]( <Date-1>, <Year-2>, null, null )
#
==================================================================================================*/

if @Date_1  is null or
   @Year_2   is null or @Year_2<0 or
   @Month_2 is not null and @Month_2 not between 1 and 12 or
   @Day_2  is not null and @Day_2  not between 1 and 31 or
   @Month_2 is null and @Day_2 is not null
   return null

----------------------------------------------------------------------------------------------------

declare @Year_1 int, @Month_1 int, @Day_1 int
select @Year_1=YEAR( @Date_1 ), @Month_1=MONTH( @Date_1 ), @Day_1=DAY( @Date_1 )

----------------------------------------------------------------------------------------------------

if @Year_1 < @Year_2 return -1
if @Year_1 > @Year_2 return  1

if @Month_2 is null return null
if @Month_1 < @Month_2 return -1
if @Month_1 > @Month_2 return  1

if @Day_2 is null return null
if @Day_1 < @Day_2 return -1
if @Day_1 > @Day_2 return  1

return 0

/*================================================================================================*/
END
GO
/*
select dbo.[AUX:CompareDate.YMD](
   CONVERT(datetime2,'11/17/2015',101),
   2015, 11, 19 ) 'Date comparison result'
select dbo.[AUX:CompareDate.YMD](
   CONVERT(datetime2,'12/17/2015',101),
   2015, 11, 19 ) 'Date comparison result'
select dbo.[AUX:CompareDate.YMD](
   CONVERT(datetime2,'12/17/2015',101),
   2015, 12, null ) 'Date comparison result'
select dbo.[AUX:CompareDate.YMD](
   CONVERT(datetime2,'12/17/2015',101),
   2015, null, null ) 'Date comparison result'
select dbo.[AUX:CompareDate.YMD](
   CONVERT(datetime2,'12/17/2015',101),
   2014, null, null ) 'Date comparison result'
*/
