如何使这个多插入结构运行得更快。一个功能和两个选择

时间:2016-12-13 16:38:36

标签: sql sql-server insert sql-insert

故事:

我需要在place表中放置随机变量,然后生成200 000条记录,但这些PID from和PIDto是来自Place表的foriegn键,它已经有200 000条记录。

当我运行此代码时,我只能在15分钟内获得5000条记录,这是不可接受的。我正在使用SQL Server 2008 R2。在网上搜索该怎么做,我无法弄明白。真的需要帮助,我刚刚知道如何优化它,所以它是显而易见的。我很感谢所有的建议。

 while @i < 200000
 begin
 insert into Item( IIT, Weight, PIDfrom, PIDto) values ('IIT'+ cast(@i as varchar(10)), rand ()*10000, 
 (select top 1 PID from Place
 order by NEWID()),
 (select top 1 PID from Place
  order by NEWID()) )
  set @i = @i + 1 
 end

1 个答案:

答案 0 :(得分:1)

您想要两个随机位置组合。我们使用join

来执行此操作
with p1 as (
      select p.*, row_number() over (order by newid()) as seqnum
      from place)
     , p2 as (
      select p.*, row_number() over (order by newid()) as seqnum
      from place)

select 'ITT' + cast(row_number() over (order by (select null)) as varchar(255)),
       rand(checksum(newid))) * 10000,
       p1.pid, p2.pid
from p1 join
     p2
     on p1.seqnum = p2.seqnum;

为了提高性能,您可以使用临时表和join

select p.*, row_number() over (order by newid)) as seqnum1,
       row_number() over (order by newid)) as seqnum2
into #tempp
from places p;

create index idx_tempp_seqnum1 on #tempp(seqnum1);
create index idx_tempp_seqnum2 on #tempp(seqnum2);

select 'ITT' + cast(row_number() over (order by (select null)) as varchar(255)),
       rand(checksum(newid))) * 10000,
       p1.pid, p2.pid
from #tempp p1 join
     #tempp p2
     on p1.seqnum1 = p2.seqnum2;