【发布时间】:2013-11-15 19:24:59
【问题描述】:
我有一个包含 900 万条记录的表,我需要遍历每一行,并且需要在每次迭代中插入到多个表中。
我的示例查询是
//this is the table with 9 million records
create table tablename
(
ROWID INT IDENTITY(1, 1) primary key ,
LeadID int,
Title varchar(20),
FirstName varchar(50),
MiddleName varchar(20),
Surname varchar(50)
)
declare @counter int
declare @leadid int
Declare @totalcounter int
set @counter = 1
Select @totalcounter = count(id) from tablename
while(@counter < @totalcounter)
begin
select @leadid = leadid from tablename
where ROWID = @counter
--perform some insert into multiple tables
--in each iteration i need to do this as well
select * from [sometable]
inner join tablename where leadid = @leadid
set @counter = @counter + 1
end
这里的问题是耗时太长,尤其是每次迭代的连接。
谁能帮我优化一下。
【问题讨论】:
-
请说明您想要达到的目标。为什么简单的加入还不够?为什么是循环和计数器?
-
理想情况下,您以基于集合的方式表达操作并完全避免循环。但目前我们无能为力,因为您向我们展示的只是您的循环基础架构代码。
-
这个带有
INNER JOIN的查询是为了什么??????仅在最后一次迭代中才有意义 - 如果您的存储过程将其作为结果集返回
标签: sql sql-server optimization