January 25, 2006 09:25 PM

Correctly Calculating Datetime Differences

Transcend DATEDIFF()’s limitations
Rating: (0)
SQL Server Magazine
InstantDoc ID #48764
T -SQL programmers share a basic and surprisingly challenging problem: correctly calculating the difference between two datetime values. SQL Server doesn't provide a built-in solution for this task, so you have to create your own.

Although SQL Server's DATEDIFF() function lets you calculate the difference between two datetime values in terms of a specified unit (e.g., year, month, day), DATE DIFF() considers only the specified unit and those higher in the temporal hierarchy— not low...

...This article is for paid Professional Members only.

Already a Professional Member? Please log in now:

NOT A PROFESSIONAL MEMBER? YOU CHOOSE:

Professional Membership

Monthly

Annual

VIP Membership

Monthly

Annual

Add a Comment

Callouts are used to call attention to one or more lines of code in a listing. In the print version of this article, the callouts will appear as highlighted code with a letter next to it. In the online version, callouts are indicated by lines such as BEGIN CALLOUT A and END CALLOUT A.

Unfortunately, the wrong code had been placed in the 48764.zip file. This code contained callout lines that were not commented, so the code would fail. I've replaced that code with the correct code. The Datetime_Difference.sql file contains all the code you see in Listings 1, 2, and 3 but without callout lines. Plus, the listing titles are treated as comments. You can obtain Datetime_Difference.sql by clicking the 48764.zip link under the "Download the Code" heading at the top of the page.

If you have any questions about the new code, please let me know. And thanks for reading SQL Server Magazine!

Karen Bemowski, senior editor
SQL Server Magazine, Windows IT Pro

Karen1/27/2009 8:31:50 AM


Possibly I am missing something obvious but what exactly is the Callout element?I am unable to compile the listing code because 'callout' is not recognised?

Bhaskar1/27/2009 12:17:11 AM


Itzik, Enjoyed your solution as always. I do believe there is a small bug concerning your treatment of seconds as revealed by the example of the difference of 3ms to midnight vs. midnight. Your solution shows 1 sec + 3 ms where correctly it should just be 3 ms. To keep the same structure and correct the bug, I added an extra derived table to use a case statement to subtract 1 from the seconds total when adding the number of seconds gives a time greater than the to_ts time.

(
SELECT keycol, from_ts, to_ts, sgn, y, m, d,
s - CASE WHEN DATEADD(second, s, from_ts) > to_ts
THEN 1 ELSE 0 END AS s
FROM

Thanks again.

Tim1/27/2006 3:40:04 PM


You must log on before posting a comment.

Are you a new visitor? Register Here
GOOGLE LINKS
SPONSORED LINKS
FEATURED LINKS