DATEDIFF() – Date Related Functions

I am unfluctuating in my creation of short articles or tidbits on Transaction SQL date/time functions.

Most, if not all, modern day computer systems collect data which contains dates and times. Many times you will want to calculate the difference between two given dates using a particular unit of measure (date part) like day, week, month, quarter or year.

Today, I will be exploring the DATEDIFF() function. This function has 12 different input parameters, units of measure (date part), that can be passed to change the resulting output.

To summarize, the function takes a date part, a start date/time variable and a end date/time variable as input returns the calculated difference in the correct unit of measure.

I will be exploring the six date part parameters that determine the units of measure

DATE PART PARAMETER TO USE
YEAR YYYY or YY
QUARTER QQ or Q
MONTH MM or M
DAY OF YEAR DY or Y
DAY DD or D
WEEK WK or WW

 

The examples below are sample calls to the function. The inputs puts are valid date part parameters and date time variables.

The output from the test is listed below.

Like any good unit test, one should try both positive and negative test cases. I am not going to explore how an EMPTY string or NULL value effect the results provided by the function.

However, the following rules apply. Any invalid date parameter results in a raised error. Any NULL values passed as parameters result in a NULL result. Any EMPTY strings result in a default date.

To make a long story short, pass one of the six date part parameters with two date/time variables to calculated the difference. Next time, I will be talking about how to use this function with Time Related Parts.

Related posts

Leave a Comment