SQL: get DATEDIFF to not return negative values

I have a request in which I run an executable file. The database contains the start time and end time. I would like to get the total time to run. So far I:

SELECT startTime, endTime,
cast(datediff(hh,starttime,endtime) as varchar)
+':'
+cast(datediff(mi,starttime,endtime)-60*datediff(hh,starttime,endtime) as varchar) AS RUNTIME
FROM applog
WHERE runID = 33871
ORDER BY startTime DESC 

When I do this, I get the expected values, as well as some unexpected ones. For example, if starttime = 2008-11-02 15: 59: 59.790 and endtime = 2008-11-02 19: 05: 41.857, then execution time = 4: -54. How to receive a query in MS SQL SMS to return the value 3:06 for this case?

Thank.

Eoin Campbell, chosen by me, is the most bulletproof for my needs. David B also knows how.

+3
source share
4 answers

Try these

Assuming 2 announced dates.

declare @start datetime
set @start = '2008-11-02 15:59:59.790'

declare @end datetime
set @end = '2008-11-02 19:05:41.857'

This will return hours / min / sec

select 
    (datediff(ss, @start, @end) / 3600), 
    (datediff(ss, @start, @end) / 60) % 60,
    (datediff(ss, @start, @end) % 60) % 60

--returns

----------- ----------- -----------
3           5           42

select
RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 3600)), 2) + ':' +
RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 60) % 60), 2) + ':' +
RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) % 60) % 60), 2)

--------
03:05:42
+3

:

-- Find Hours, Minutes and Seconds in between two datetime
DECLARE @First datetime
DECLARE @Second datetime
SET @First = '04/02/2008 05:23:22'
SET @Second = getdate()

SELECT DATEDIFF(day,@First,@Second)*24 as TotalHours,
DATEDIFF(day,@First,@Second)*24*60 as TotalMinutes,
DATEDIFF(day,@First,@Second)*24*60*60 as TotalSeconds
+1

(). datepart.

. MSDN DATEDIFF (Transact-SQL).

"mi", "hh" .

(, ss s) ( , ).

+1

:

DECLARE @applog TABLE
(
  runID int,
  starttime datetime,
  endtime datetime
)

INSERT INTO @applog (runID, starttime, endtime)
SELECT 33871, '2008-11-02 15:59:59.790', '2008-11-02 19:05:41.857'
-------------------
SELECT
  SUBSTRING(convert(varchar(30), DateAdd(mi, duration, 0), 121),
  12, 5) as prettyduration
FROM
(
SELECT starttime, DateDiff(mi, starttime, endtime) as duration
FROM @applog
WHERE runID = 33871
) as sub

24 , . , .

0

Source: https://habr.com/ru/post/1699084/


All Articles