MS sql 服务器循环通过巨大的表



我有一个有 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

这里的问题是这花费的时间太长,尤其是每次迭代的连接。

有人可以帮我优化一下吗?

是的,您的联接需要很长时间,因为两个表之间没有指定联接条件,因此您正在创建笛卡尔积。这肯定需要一段时间。

如果要对此进行优化,请指定要联接这些表的内容。

如果它仍然很慢,请查看相应的索引。

看起来您正在尝试查找sometable中与tablename中的行具有相同leadid的所有行?如果是这样,一个简单的连接应该可以工作

select t2.*
from tablename t2 inner join sometable t2
     on t1.leadid=t2.leadid

只要你有一个关于leaid的索引,你应该没有任何问题

你到底想做什么?

最新更新