Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting from a date the number of days in SQL Server

I would like to subtract number of days from a date with the format (YY-MM-DD HH:MI:SS). Is there any automated function to perform this or would it be exhaustive coding to perform this task. I'm writing a stored procedure which encompasses the above task.

To be more clear lets say this is the date 2011-12-07 06:05:19.200 and I want to subtract 19 days from it and the result will be 2011-11-18 06:05:19.200 and the number of days is going to be a parameter in the SP

like image 484
Sree Avatar asked Dec 17 '22 03:12

Sree


2 Answers

You deleted your identical question where I answered before, but here's a function that does what you need;

CREATE FUNCTION SUBTRACT_DAYS( @date AS DATETIME, @days AS INT )
RETURNS DATETIME
BEGIN
  RETURN DATEADD(dd, -@days, @date);
END;

SELECT dbo.SUBTRACT_DAYS('2011-12-07 06:05:19.200', 19);

> 2011-11-18 06:05:19.200
like image 192
Joachim Isaksson Avatar answered Feb 11 '23 12:02

Joachim Isaksson


How about this:

CREATE PROCEDURE dbo.DoSomethingUseful  @InputDate DATETIME, @NumberOfDays INT
AS BEGIN

   SELECT DATEADD(Day, @NumberOfDays, @InputDate)

END

and then call it like this:

EXEC dbo.DoSomethingUseful @InputDate = '2011-12-07T06:05:19.200', @NumberOfDays = -19

returns:

2011-11-18 06:05:19.200
like image 40
marc_s Avatar answered Feb 11 '23 13:02

marc_s