Wednesday, January 03, 2007

Difference of two datetime columns caused overflow at runtime

You want to get the difference in seconds between 2 dates, you can do that by using datediff(s,date1,date2)
However if the difference in seconds is greater than a value that can be stored in an integer then you will get the following message

Server: Msg 535, Level 16, State 1, Line 1
Difference of two datetime columns caused overflow at runtime.

Run this to see that message
SELECT DATEDIFF(s,'19000101','20060101')

So what can you do to eliminate this?

You can convert to bigint and then multiply by 60

SELECT CONVERT(BIGINT,DATEDIFF(mi,'19000101','20060101'))* 60


To make sure that the match is correct you can compare these two


SELECT DATEDIFF(s,'19700101','20060101')

SELECT CONVERT(BIGINT,DATEDIFF(mi,'19700101','20060101'))* 60

They both return 1136073600

No comments: