Converting Milliseconds to Days, hours, minutes and seconds
Asked Answered
L

1

9

i have a bigint field in Microsoft SQL Server 2008R2 filled with ticks (A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.)

http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx

and i need to convert the sum of all records to Days:Hours:Minutes:Seconds:Milliseconds.

it works for a single record:

SELECT CONVERT(TIME, DATEADD(ms, duration/10000, 0)) FROM tblMediaFileProperties WHERE FileId = '6C0A849D-95B4-4755-A923-B9DD8F1AF23E'

but if a sum it up to all records using:

SELECT CONVERT(TIME, DATEADD(ms, SUM(duration/10000), 0)) FROM tblMediaFileProperties 

i get a:

Arithmetic overflow error converting expression to data type int.

i know the overflow comes from the CONVERT to Data Type TIME Function...

help's appreciated, thanks!

Linger answered 6/10, 2012 at 7:39 Comment(0)
B
8

It's too big for DATEADD which only accepts an int.
Break it into two parts: seconds, then milliseconds.

SELECT CONVERT(TIME,
          DATEADD(ms, SUM(duration/10000 % 1000),
          DATEADD(ss, SUM(duration/10000000), 0)))
FROM tblMediaFileProperties 

And if your total duration goes above 1 day, you can use this to get the days and hr:min:sec:ms separately. It's a matter of cast and string concat if you actually want the result in textual form.

declare @duration bigint
set @duration = 1230000000
SELECT @duration/10000/1000/60/60/24 DAYS,
       CONVERT(TIME,
          DATEADD(ms, SUM(@duration/10000 % 1000),
          DATEADD(ss, SUM(@duration/10000000), 0))) HR_MIN_SEC
Bronwen answered 6/10, 2012 at 7:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.