Based on the other question you posted ...
I commented there that you should only format a date when you are presenting it to the user in the GUI layer - this is what Kornfeld Eliyahu Peter is presenting in Solution 1.
However your other question seemed to imply that you were trying to find rows where the next marriage anniversary was within the next 7 days.
The way you are formatting the data to do the WHERE clause is messy and unnecessary.
Consider using something like this instead:
Select
em.Name,
DATEADD(YY, DATEPART(YYYY, getdate()) - DATEPART(YYYY,Marriagedate), Marriagedate) AS Current_data,
DATEADD(YY, DATEPART(YYYY, getdate()) - DATEPART(YYYY,Marriagedate) + 1, Marriagedate) AS Next_Anniv,
HowLongMarried = DATEDIFF(YEAR,Marriagedate,GETDATE())
from
EmployeeMaster em
inner join EmpMarriageDate ed on em.Id=ed.EmployeeId
where
DATEADD(YY, DATEPART(YYYY, getdate()) - DATEPART(YYYY,Marriagedate), Marriagedate)
BETWEEN GETDATE() AND DATEADD(dd, 7, GETDATE())
OR
DATEADD(YY, DATEPART(YYYY, getdate()) - DATEPART(YYYY,Marriagedate) + 1, Marriagedate)
BETWEEN GETDATE() AND DATEADD(dd, 7, GETDATE())
You can make it even clearer by using a CTE ...
with BaseData AS
(
Select
em.Name,
DATEADD(YY, DATEPART(YYYY, getdate()) - DATEPART(YYYY,Marriagedate), Marriagedate) AS Current_data,
DATEADD(YY, DATEPART(YYYY, getdate()) - DATEPART(YYYY,Marriagedate) + 1, Marriagedate) AS Next_Anniv,
HowLongMarried = DATEDIFF(YEAR,Marriagedate,GETDATE())
from
EmployeeMaster em
inner join EmpMarriageDate ed on em.Id=ed.EmployeeId
)
SELECT [Name], Current_data, HowLongMarried
FROM BaseData
where
Current_data BETWEEN GETDATE() AND DATEADD(dd, 7, GETDATE())
OR
Next_Anniv BETWEEN GETDATE() AND DATEADD(dd, 7, GETDATE())
Note that if
Marriagedate
column has been defined as a
DateTime
rather than
Date
you can cast the results to
Date
CAST(Current_data as date)