Get all dates between two dates in SQL Server -
how dates between 2 dates?
i have variable @maxdate
storing maximum date table. want dates between @maxdate
, getdate()
, want store these date in cursor.
so far have done follows:
;with getdates ( select dateadd(day,1,@maxdate) thedate union select dateadd(day,1, thedate) getdates thedate < getdate() )
this working when trying store these values in cursor
set @datecursor=cursor select thedate getdates
compilation error
incorrect syntax near keyword 'set'.
how solve this.
thanks in advance
my first suggestion use calendar table, if don't have one, create one. useful. query simple as:
declare @mindate date = '20140101', @maxdate date = '20140106'; select date dbo.calendar date >= @mindate , date < @maxdate;
if don't want to, or can't create calendar table can still on fly without recursive cte:
declare @mindate date = '20140101', @maxdate date = '20140106'; select top (datediff(day, @mindate, @maxdate) + 1) date = dateadd(day, row_number() over(order a.object_id) - 1, @mindate) sys.all_objects cross join sys.all_objects b;
for further reading on see:
- generate set or sequence without loops – part 1
- generate set or sequence without loops – part 2
- generate set or sequence without loops – part 3
with regard using sequence of dates in cursor, recommend find way. there set based alternative perform better.
so data:
date | it_cd | qty 24-04-14 | i-1 | 10 26-04-14 | i-1 | 20
to quantity on 28-04-2014 (which gather requirement), don't need of above, can use:
select top 1 date, it_cd, qty t it_cd = 'i-1' , date <= '20140428' order date desc;
if don't want particular item:
select date, it_cd, qty ( select date, it_cd, qty, rownumber = row_number() over(partition ic_id order date desc) t date <= '20140428' ) t rownumber = 1;
Comments
Post a Comment