【发布时间】:2015-04-30 13:20:53
【问题描述】:
我需要在 PL-SQL 中执行一个语句,该语句选择一个 ID,对这些 ID 的子集执行连接...在下面的示例中,我有大约 700000 个客户,并且一个 远 比此示例中的简单 while 循环中显示的更复杂的查询...我的性能很差,我很好奇将我当前的 PL-SQL 分割成“块”是否会提高性能?
目前:
declare
TYPE customerIdTabType IS TABLE OF customer.CustomerId%TYPE INDEX BY BINARY_INTEGER;
vars customerIdTabType;
-- maybe this should be in a table?
cursor c is
select
c.CustomerId
from customer c
join productcustomers pc on pc.customerid = c.customerid
join product p on p.productid = pc.productid
where
c.CustomerId > 1000;
begin
open c;
loop
fetch c bulk collect into vars limit 1000;
-- here is where instead of looping through each item in vars
-- i actually want to 'join' to the 1000 that i have.
forall i in 1..vars.count
insert into xxx (CustomerId)
values (vars(i));
commit;
exit when vars.count = 0;
end loop;
close c;
end;
- 将 CustomerId 列表选择到“临时”存储容器中 - 不确定选项是什么?
- 通过将这些 CustomerId 加入到另一个查询中,分批处理这些 CustomerId... 1000
- 将所有结果插入物理表中
所以,在 T-SQL 中可能是..
-- create a temp table
create table #MyTempTable (
id int identity(1,1)
,customerid varchar(10)
)
-- populate that table
insert into #MyTempTable
select Customerid
from schema.Customers
-- create some vars for looping
declare i int, c int;
select i = 0;
select c = count(*) from #MyTempTable;
-- loop through the original set in 'chunks' of 1000
while i < c
begin
insert into SomeOtherTable
(CustomerId, CustomerAttribute)
select
o.CustomerId
,o.CustomerAttribute
from OtherTable o
join #MyTempTable t
on o.CustomerId = t.CustomerId
where
t.Id between i and i+1000 -- from 0 to 1000
set @i = i+1000 -- next loop will be from 1000 to 2000
end
谢谢
【问题讨论】: