Skip to content
Advertisement

Function to check if a date is a Christmas day or New Years day

I am creating a function in SQL Server to validate if given date is a Christmas day or new year’s day. Please kindly advise if following code is OK:

Declare @paramDate date
....
IF Month(@paramDate) = 12 and DAY(@paramDate) = 25
     or Month(@paramDate) = 1 and DAY(@paramDate) = 1
BEGIN
   ....

Above is the simplest way I can think of regardless or timezone and date format

Advertisement

Answer

I would create a table-valued function like this, rather than what I suspect is a scalar function based on the syntax in your question. Your checks are fine, I don’t think they can be any simpler and still be intuitive, but another way to test for specific dates is to compare to DATEFROMPARTS():

CREATE FUNCTION dbo.IsSpecificHoliday
(
  @d date
)
RETURNS table WITH SCHEMABINDING
AS
  RETURN 
  (
      SELECT IsSpecificHoliday = CASE @d
        WHEN DATEFROMPARTS(YEAR(@d), 12, 25) THEN 1
        WHEN DATEFROMPARTS(YEAR(@d), 1,  1) THEN 1
        ELSE 0 END
  );

Sample usage:

CREATE TABLE dbo.Dates(TheDate date);

INSERT dbo.Dates(TheDate) VALUES
  ('19701214'),('19991225'),('20400101');

SELECT d.TheDate, f.IsSpecificHoliday
  FROM dbo.Dates AS d 
  CROSS APPLY dbo.IsSpecificHoliday(d.TheDate) AS f;

Results:

TheDate IsSpecificHoliday
1970-12-14 0
1999-12-25 1
2040-01-01 1

You could also always consider a calendar table (for this and so many other purposes) and have a calculated or pre-populated column there like IsSpecificHoliday and simply join to that on the date column.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement