Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005, Calculating upcoming birthdays from date of birth

This one has bugged me for a while now. Recently when revisiting some code I wrote for a customer a few years ago I was wondering if there is a more elegant solution to the problem.

The customer stores all of their clients information including date of birth (date time field)

They run an extract every Monday that retrieves any customer whose birthday will fall within the following week.

I.e. if the extract was run on Monday Jan 1st, Customers whose birthday fell between (and including) Monday Jan 8th -> Sunday Jan 14th would be retrieved.

My solution was to use the Datepart(dy) function and calculate all upcoming birthdays based off the customers date of birth converted to day of year, adding some logic to include for the extract being run at the end of a year. The problem was that using Day of year throws results off by 1 day if the customer was born on a leap year and / or the extract is run on a leap-year after the 29th of Feb, so once again I had to add more logic so the procedure returned the expected results.

This seemed quite over-kill for what should be a simple task For simplicity let’s say the table 'customer' contains 4 fields, first name, last name, dob, and address.

Any suggestions on how to simplify this would really be appreciated

Wes

like image 405
Wes Price Avatar asked Sep 20 '10 13:09

Wes Price


People also ask

How to calculate birthdate in SQL?

Conclusion. We can calculate the age of a person using their date of birth using these functions altogether: NOW(), DATEDIFF(), FROM_DAYS(), and DATE_FORMAT(). The formula to convert the date of birth into age is DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),'DATE_OF_BIRTH')), '%Y').

How do I calculate years from a date in SQL?

The EXTRACT() function returns a number which represents the year of the date. The EXTRACT() function is a SQL standard function supported by MySQL, Oracle, PostgreSQL, and Firebird. If you use SQL Server, you can use the YEAR() or DATEPART() function to extract the year from a date.

How do I find the Getdate in SQL Server?

SQL Server GETDATE() FunctionThe GETDATE() function returns the current database system date and time, in a 'YYYY-MM-DD hh:mm:ss.mmm' format. Tip: Also look at the CURRENT_TIMESTAMP function.

What is current date SQL?

MySQL SYSDATE() FunctionThe SYSDATE() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH:MM:SS" (string) or as YYYYMMDDHHMMSS (numeric).


1 Answers

Would something like this work for you?

select * from Customers c 
where dateadd(year, 1900-year(dob), dob) 
    between dateadd(year, 1900-year(getdate()), getdate())
    and dateadd(year, 1900-year(getdate()), getdate())+7
like image 87
Denis Valeev Avatar answered Sep 28 '22 08:09

Denis Valeev