DATEADD() – Date Related Functions

I am steady 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 add or subtract a fixed number of years, months, or etc from a date time variable.

Today, I will be exploring the DATEADD() function. This function has 13 different input parameters that can be passed to change the resulting output.

To summarize, the function takes a date part, a offset number, and date/time variables as input returns a new date/time variable adjusted by adding or subtracting the offset.

I will be exploring the seven date part parameters that adjust date/time variable by a fixed date offset.

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
DAY OF WEEK DW or W

 

The examples below are sample calls to the function. The inputs puts are valid numeric offsets 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. I am only going to do this for one date part since they all act the same.

The output from the test is listed below. Any invalid data to the numeric offset results in a raised error. Any NULL values passed as a date time result in NULL and EMPTY strings result in a default date.

To make a long story short, pass one of the seven date part parameters with a valid offset number to adjust your current date time variable. Next time, I will be talking about how to use this function with Time Related Parts.

Related posts

Leave a Comment