Total Pageviews

2016/02/04

[Microsoft SQL Server] How to subtract a year in SQL

Problem
I have a select SQL statement as bellows:
SELECT sta_date
FROM dbm031fa
WHERE year(sta_date) = year(CURRENT_TIMESTAMP)-2
If I would like to get the value of sta_date is the value in database subtract one year, how to do it?


How To
Microsoft SQL Server had a build-in function, DATEADD, to fulfill this requirements.
The SQL statement can be modified as following:
SELECT sta_date,
       DATEADD(YEAR, -1, sta_date)
FROM dbm031fa
WHERE year(sta_date) = year(CURRENT_TIMESTAMP)-2


Reference
[1] https://msdn.microsoft.com/zh-tw/library/ms186819(v=sql.120).aspx

No comments: