This function is used to add or subtract specified time interval from dates in SQL Server. Generally DATEADD function will take 3 arguments.
Declaration of DATEADD function:
DATEADD (datepart, number, date)
In this function
1st Argument “datepart” is the interval type we need to add or subtract for example day, month, year, hour, minute, second.
Datepart can be one of the following:
datepart
|
Abbreviation
|
year
|
yy, yyyy
|
quarter
|
qq, q
|
month
|
mm, m
|
dayofyear
|
dy, y
|
day
|
dd, d
|
week
|
wk, ww
|
weekday
|
dw, w
|
hour
|
hh
|
minute
|
mi, n
|
second
|
ss, s
|
millisecond
|
ms
|
microsecond
|
mcs
|
nanosecond
|
ns
|
2nd Argument the number is the amount of datepart units to add or subtract. For example if datepart was d and the number was 3 then it would add three days to the date specified.
3rd Argument date is the date to add/subtract the number of dateparts from. It can either be a column in the database, a constant value or a function such as GETDATE() which would return the current date and time.
Examples of DATEADD Function:
Ex: 1
Suppose if we want to add one month to present date we need to write the query like this
SELECT GETDATE() AS CurrentDate,DATEADD (mm, 1, GETDATE()) AS NewDate
Output:
CurrentDate
|
NewDate
|
2013-03-23 15:48:19.440 | 2013-04-23 15:48:19.440 |
Ex: 2
Suppose if we want to subtract one month from present date we need to write the query like this
SELECT GETDATE() AS CurrentDate,DATEADD (mm, -1, GETDATE()) AS NewDate
Output:
CurrentDate
|
NewDate
|
2013-03-23 15:48:19.440 | 2013-02-23 15:48:19.440 |
Ex: 3
We have Orders table like this
OrderId
|
OrderName
|
ShippingDate
|
1
|
IPhone 5
|
2013-03-23 15:48:19.440 |
Now I need to add 15 days to “OrderDate” for that we need to write the query like this
SELECT OrderId, OrderName, DATEADD(dd,15,OrderDate) As OrderDate FROM Orders
Output:
OrderId
|
OrderName
|
ShippingDate
|
1
|
IPhone 5 | 2013-04-07 15:50:58.153 |