如何将潜在的循环查询设置为基于?

时间:2017-11-14 18:11:27

标签: sql sql-server tsql sql-server-2012

我现在有类似的东西 -

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

如何将其从光标更改为基于集合的解决方案? 注意:添加了获取行

1 个答案:

答案 0 :(得分:1)

您不需要游标来解决此OP。使用CROSS加入而不是 这种方式比Cursor快。

见下文。
仅供参考。 mydates表只是一个随机日期示例,因为我不想输入它们

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)