Home How to turn potential loop query to set based?
Reply: 1

How to turn potential loop query to set based?

Da Best
1#
Da Best Published in 2017-11-14 18:11:26Z

I have something like this currently -

declare @thisDate smalldatetime

create table #theseDates (thisDate smalldatetime)
insert into #theseDates(thisDate)
values ('11/1/2016', '5/1/2017', '9/30/2017)

create table #someData (productid int, productname varchar(32), productprice float, productsolddate smalldatetime)

declare date_cursor cursor for
select thisDate from #theseDates

open date_cursor
fetch next for date_cursor into @thisDate

while @@fetch_status = 0
begin
   insert into #someData(soldid, productid, productname, productprice, productsolddate)
   select soldid, productid, productname, productprice, productsolddate
   from soldproducts
   where productsolddate between @thisDate and getdate()

   fetch next from date_cursor into @thisDate
end

close date_cursor
deallocate date_cursor

How do I change this from a cursor to a set-based solution? NOTE: added fetch line

maSTAShuFu
2#
maSTAShuFu Reply to 2017-11-15 20:53:05Z

You don't need a cursor to solve this OP. Use CROSS Join instead
This way faster than Cursor.

See below.
FYI. the mydates table is just a random date example because I don't want type them

declare @myproducts table (prodid int, proddesc varchar(30), prodprice money, solddate date)

insert into @myproducts
values 
(1,'prod 1',1,dateadd(day,-1,getdate())),
(2,'prod 2',10,dateadd(day,-10,getdate())),
(3,'prod 3',100,dateadd(day,-5,getdate())),
(1,'prod 1',1.5,dateadd(day,-6,getdate())),
(2,'prod 2',8.99,dateadd(day,-20,getdate())),
(3,'prod 3',95,dateadd(day,-15,getdate())),
(1,'prod 1',0.89,dateadd(day,-2,getdate()))

select * from @myproducts


declare @mydates table (mydate date)

/* reporting datefrom */

insert into @mydates
values (dateadd(day,-11,getdate())),(dateadd(day,-20,getdate())),(dateadd(day,-3,getdate()))

select * from @mydates

/* apply cross join to distribute the datefrom but should only be to data where solddate is between datefrom and today */

-- insert statement to dump all qualified data or not
select p.*,d.mydate [DateFrom] from @myproducts p
cross join @mydates d
where solddate between mydate and cast(getdate() as date)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.353658 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO