Sql-server – Date variable to filter result for all previous years

datequerysql server

I am querying a sales order table and need to add a variable so that the query always returns a customer list for all customers that have not purchased this year. I don't want to hard code this years' date into WHERE or HAVING, but instead am interested to somehow have this dynamically pass the correct variable so that it also works in the future without changing the code. I appreciate any suggestions. Hope this is clear enough.

Best Answer

There are many ways to get the beginning of this year, I think the most intuitive is DATEFROMPARTS():

DECLARE @BeginningOfThisYear date = DATEFROMPARTS(YEAR(SYSUTCDATETIME()),1,1);

SELECT ... FROM dbo.Customers AS c
WHERE NOT EXISTS 
(
  SELECT 1 FROM dbo.Orders 
    WHERE CustomerID = c.CustomerID
    AND OrderDate >= @BeginningOfThisYear
);

Less intuitive ways include:

DECLARE @BeginningOfThisYear date = DATEADD(DAY, 
  1-DATEPART(DAYOFYEAR, SYSUTCDATETIME()), 
  SYSUTCDATETIME()
);

And downright terrible ways include:

DECLARE @BeginningOfThisYear date = CONVERT(date,
  CONCAT(YEAR(SYSUTCDATETIME()),'0101'));