Reputation: 238
How can we deduce the date falling exactly 3 months prior to the current date in SQL Server?
Upvotes: 0
Views: 2551
Reputation: 1087
Dateadd can give the same result for three different dates.
Select DateAdd(Month, -3, '2024-05-29')
Select DateAdd(Month, -3, '2024-05-30')
Select DateAdd(Month, -3, '2024-05-31')
All give the same result namely 2024-02-29, recognising that 3 months is a quarter using:
Select dateAdd(DD, -91, '2024-05-31')
Select dateAdd(DD, -91, '2024-05-30')
Select dateAdd(DD, -91, '2024-05-29')
Will give 2024-03-01, 2024-02-29, 2024-02-28 respectively.
So the answer depends on what you are trying to achieve
Upvotes: 1
Reputation: 14928
Use DATEADD()
function
SELECT DATEADD(M, -3,GETDATE()) AS WithTime,
CAST(DATEADD(M, -3, GETDATE()) AS DATE) AS WithoutTime
If you are working on newest versions of SQL Server (2012+) I would recommand to use TRY_CONVERT()
or TRY_CAST()
functions.
Upvotes: 0
Reputation: 31991
use dateadd
select convert(date, dateadd(month,-3,getdate()))
output
16/07/2018 00:00:00
Upvotes: 4