Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract two dates in Microsoft SQL Server

I want to subtract 2 dates in MS SQL Server.

Example:

Current date      Last used date
'2016-03-30'      '2015-02-03'

Current date refers to today's date, "Last used date" is a measure.

How to write a query in SQL Server?

I have this but doesn't work (it says "Operand data type is invalid for subtract operator")

select 
    CONVERT(DATE, GETDATE()) - CONVERT(DATE, LastUsedDate) 
from 
    databasename 
like image 820
Shivang Avatar asked Mar 29 '16 22:03

Shivang


People also ask

How do I subtract one date from another in SQL Server?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference. Its value can be year , quarter , month , day , minute , etc.

How do you substract a date in SQL?

Discussion: If you would like to subtract dates or times in SQL Server, use the DATEADD() function. It takes three arguments. The first argument is the date/time unit – in our example, we specify the day unit.


2 Answers

SELECT     DATEDIFF(day,'2014-06-05','2014-08-05')     AS DiffDate

Output DiffDate 61

More practice please refer below W3 school:

https://www.w3schools.com/sql/func_sqlserver_datediff.asp

like image 177
Dipen Patel Avatar answered Sep 21 '22 16:09

Dipen Patel


Here you don't have to cast GETDATE() to date, as it is already datetime datatype. So your query will be as follows

SELECT DATEDIFF(day,CAST(LastUsedDate as date),GETDATE()) AS DifferneceDays
FROM TableName
like image 31
Vinay Tedla Avatar answered Sep 24 '22 16:09

Vinay Tedla