DATEDIFF() – Sub-second Functions

I am a devoted 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 milliseconds, microseconds, and nanoseconds.

Today, I will be exploring the DATEDIFF() function. This function has 12 different input parameters 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 three date part parameters that determine the units of measure related to less than a second in time.

DATE PART PARAMETER TO USE
MILLISCOND MS
MICROSECOND MCS
NANASECOND NS

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.

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 three time part parameters with two date/time variables to calculated the difference. Next time, I will be talking how to use the ISDATE() function.

Related posts

Leave a Comment