SQL Query of the Day #060120141300

Query:

SELECT fname, lname, hire_date
FROM EMPLOYEES
WHERE DATEDIFF(yy, hire_date,GETDATE()+30) > DATEDIFF(yy, hire_date,GETDATE())

Function: Returns the name and hire date of all employees whose hire-date anniversaries fall within the next thirty days. The DATEDIFF() method returns the difference, in units given by the first parameter, between the second and third parameters. So if the difference in years between an employee’s hire date and thirty days from now exceeds the difference in years between the employee’s hire date and today, you know that employee will have a hire-date anniversary within the next thirty days. For example, if today is 6 Jan 2014 (as it is), then GETDATE()+30 = 5 Feb 2014. If an employee was hired on 10 Jan 2012, (DATEDIFF(yy, 10Jan2012,5Feb2014) = 2) > (DATEDIFF(yy, 10Jan2012,6Jan2014) = 1). If, however, an employee was hired on 10 Feb 2012, (DATEDIFF(yy, 10Feb2012,5Feb2014) = 1) !> (DATEDIFF(yy, 10Feb2012,6Jan2014) = 1), and if an employee was hired on 2 Jan 2012, (DATEDIFF(yy, 2Jan2012,5Feb2014) = 2) !> (DATEDIFF(yy, 2Jan2012,6Jan2014) = 2).

Source: Henderson, Ken. The Guru’s Guide to Transact-SQL. Reading, MA: Addison-Wesley, 2000. Print. (p. 25)

Comments: Most database engines will already have an API in place to keep you from reinventing the wheel and, in so doing, crushing your own foot. Good to know, isn’t it? Have a pleasant and productive day.

Leave a Comment

Filed under Uncategorized

Leave a Reply