I have a table in my database the records start and stop times for a specific task. Here is a sample of the data:
Start Stop
9/15/2008 5:59:46 PM 9/15/2008 6:26:28 PM
9/15/2008 6:30:45 PM 9/15/2008 6:40:49 PM
9/16/2008 8:30:45 PM 9/15/2008 9:20:29 PM
9/16/2008 12:30:45 PM 12/31/9999 12:00:00 AM
I would like to write a script that totals up the elapsed minutes for these time frames, and wherever there is a 12/31/9999 date, I want it to use the current date and time, as this is still in progress.
How would I do this using Transact-SQL?
SQL> create or replace function elapsed( 2 ts1 in timestamp, 3 ts2 in timestamp 4 ) return varchar2 sql_macro(scalar) is 5 begin 6 return ' 7 extract(day from (ts2-ts1))*86400+ 8 extract(hour from (ts2-ts1))*3600+ 9 extract(minute from (ts2-ts1))*60+ 10 extract(second from (ts2-ts1))'; 11 end; 12 / Function created.
The cpu time is the total time spent by the cpu resources on a server. If a server has five cpus, and each cpu runs 3 milliseconds concurrently with the other cpus, then the total cpu time is 15 milliseconds. The elapsed time is the total time taken by SQL Server.
SELECT SUM( CASE WHEN Stop = '31 dec 9999'
THEN DateDiff(mi, Start, Stop)
ELSE DateDiff(mi, Start, GetDate())
END ) AS TotalMinutes
FROM task
However, a better solution would be to make the Stop field nullable, and make it null when the task is still running. That way, you could do this:
SELECT SUM( DateDiff( mi, Start, IsNull(Stop, GetDate() ) ) AS TotalMinutes FROM task
I think this is cleaner:
SELECT SUM(
DATEDIFF(mi, Start, ISNULL(NULLIF(Stop,'99991231'), GetDate()))
) AS ElapsedTime
FROM Table
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With