How to get the dates between two dates?
I have a variable @MAXDATE
which is storing the maximum date from the table. Now I want to get the all dates between @Maxdate
and GETDATE()
and want to store these date in a cursor.
So far I have done as follows:
;with GetDates As
(
select DATEADD(day,1,@maxDate) as TheDate
UNION ALL
select DATEADD(day,1, TheDate) from GetDates
where TheDate < GETDATE()
)
This is working perfectly but when I am trying to store these values in a cursor
SET @DateCurSor=CURSOR FOR
SELECT TheDate
FROM GetDates
Compilation Error
Incorrect syntax near the keyword 'SET'.
How to solve this.
Thanks in advance
This can be considered as bit tricky way as in my situation, I can't use a CTE table, so decided to join with "sys.all_objects" and then created row numbers and added that to start date till it reached the end date.
See the code below where I generated all dates in Jul 2018. Replace hard coded dates with your own variables(tested in SQL Server 2016):
Easily create a Table Value Function that will return a table with all dates. Input dates as string You can customize the date in the the format you like '01/01/2017' or '01-01-2017' in string formats (103,126 ...)
Try this
To execute the function do this:
The output will be
This is the method that I would use.
Here is a similar example, but this time the dates are spaced one hour apart to further aid understanding of how the query works:
As you can see, the query is fast, accurate and versatile.
My first suggestion would be use your calendar table, if you don't have one, then create one. They are very useful. Your query is then as simple as:
If you don't want to, or can't create a calendar table you can still do this on the fly without a recursive CTE:
For further reading on this see:
With regard to then using this sequence of dates in a cursor, I would really recommend you find another way. There is usually a set based alternative that will perform much better.
So with your data:
To get the quantity on 28-04-2014 (which I gather is your requirement), you don't actually need any of the above, you can simply use:
If you don't want it for a particular item: