Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom code similar to DATEDIFF_BIG in SQL Server 2014

I am using SQL Server 2014. I am facing a problem when I want to compare previous row date time with current row in second. The error states:

The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.

SQL Server 2016 solved this issue with DATEDIFF_BIG but that function is not supported in SQL Server 2014. And currently there are no plans to change database server with SQL Server 2016.

Any alternative solution would be appreciated.

SELECT ROW_NUMBER() OVER (Order by A.MDetailID) as Row
  , DATEDIFF(SECOND, A.CreatedDate, LEAD(A.CreatedDate,1,0) OVER (ORDER BY A.CreatedDate))
FROM dbo.tbl_VehicleLiveMovementDetail A
like image 457
Majedur Avatar asked Jan 17 '19 05:01

Majedur


People also ask

What is the difference between Dateadd and datediff?

The DateAdd function adds a number of units to a date/time value. The result is a new date/time value. You can also subtract a number of units from a date/time value by specifying a negative value. The DateDiff function returns the difference between two date/time values.

How do I get the difference between two dates in SQL?

The DATEDIFF() function returns the difference between two dates.

How do I convert a date to month and year in SQL?

SQL Server DATEFROMPARTS() Function The DATEFROMPARTS() function returns a date from the specified parts (year, month, and day values).

Can we use datediff in where clause?

Note: DATEADD and DATEDIFF SQL function can be used in the SELECT, WHERE, HAVING, GROUP BY and ORDER BY clauses.


1 Answers

According to your code,

LEAD(A.CreatedDate,1,0) OVER (ORDER BY A.CreatedDate)

LEAD function provides access to a row at a given physical offset that follows the current row but at the last row LEAD function not found any subsequent row so it return default datetime '1900-01-01 00:00:00' . For this case you need to compare with default datetime like as following....

case when LEAD(A.CreatedDate,1,0) OVER (ORDER BY A.CreatedDate)='1900-01-01 00:00:00' then A.CreatedDate else LEAD(A.CreatedDate,1,0) OVER (ORDER BY A.CreatedDate) end

which would not be optimum solution for you.

If you use LEAD(A.CreatedDate,1,A.CreatedDate) instead of LEAD(A.CreatedDate,1,0), you would not be required to use any case statement and the solution would be optimum like as following...

SELECT 
ROW_NUMBER() OVER (Order by A.MDetailID) as Row,
DATEDIFF(SECOND, A.CreatedDate, LEAD (A.CreatedDate,1,A.CreatedDate)OVER (ORDER BY A.CreatedDate))Result
FROM dbo.tbl_VehicleLiveMovementDetail A
like image 89
Osman Avatar answered Nov 11 '22 16:11

Osman