sqldatedatetimesubtraction

SQL - Subtract Date with Integer


I have a document that has "Delivery Date" and "Days to Deliver" fields I would like to calculate a "Dispatch Date" = "Delivery Date" subtract "Days to Deliver".

Currently I'm trying:

dbo.t0.docduedate-dbo.crd1.daystodeliver`

I am getting a datetime format error for above. Where am I getting this wrong?


Solution

  • Assuming that you are using SQL server, you could use SQL function DATEADD().
    First parameter is d which stands for day.
    Second parameter is how many days you want to add and putting minus (-) in front instead of adding subtracts the value.
    Last parameter is initial date itself that you want to be manipulated.
    You might need to cast input values to appropriate types - second parameter has to be integer.

    SELECT DATEADD(d,-[DaysToDeliver], [DeliveryDate]) AS 'Dispatch Date' FROM [TABLE]