10
Answers

Get 24 months rollover value from database

I am using a Stored Procedure to get data from database. I want to get the values based on current date and move 23 months before current date. 

In a Stored Procedure I declare current date with

DECLARE @CurrentDate AS DateTime = GetDate();

Data for current month with a formula from I will only mention the date part because is too long and I know the rest is correct

WHERE DATEPART(YEAR, tr.DataInitierii)=DATEPART(YEAR, @CurrentDate) AND DATEPART(MONTH, tr.DataInitierii)=DATEPART(MONTH, @CurrentDate)

and I try to get previous values with

WHERE DATEPART(YEAR, tr.DataInitierii)=DATEPART(YEAR, DATEADD(MONTH,-1,@CurrentDate)) AND DATEPART(MONTH, tr.DataInitierii)=DATEPART(MONTH, DATEADD(MONTH,-1,@CurrentDate))

and so on until

WHERE DATEPART(YEAR, tr.DataInitierii)=DATEPART(YEAR, DATEADD(MONTH,-23,@CurrentDate)) AND DATEPART(MONTH, tr.DataInitierii)=DATEPART(MONTH, DATEADD(MONTH,-23,@CurrentDate))

but the result is NULL despite having data in the database.

 

What am I doing wrong within the condition?

Answers (10)