【问题标题】:Advice about INSERT statement performance in SQL Server关于 SQL Server 中 INSERT 语句性能的建议
【发布时间】:2016-11-12 07:12:38
【问题描述】:

我需要在 SQL Server 中生成随机数并将这些代码写入表中。我使用的SQL语句如下:

while (select count(code) from tb_random) <1000000
begin
SET NOCOUNT ON
declare @r int
set @r = rand()*10000000
insert into tb_random values(@r)
end

完成此查询需要 20 多小时。你能给我一个解决这个性能问题的想法吗?

【问题讨论】:

  • 现在你有了数字,你需要再做一次吗?另外,你意识到你不一定有唯一的数字,对吧?
  • 实际上,我需要超过 10,000,000 个代码。这意味着我必须重复10次以上。我知道如何创建唯一 ID。我只关心性能并且可以应用其他随机算法。谢谢
  • 你的 tb_random 模式是什么?
  • 如果你告诉我们你为什么需要这个可能会有所帮助。这对我来说似乎不对,如果我们知道更多,您最终可能会得到一个简单的解决方案......
  • 感谢 JBrooks。下面的想法帮助我解决了这个问题。

标签: sql sql-server random


【解决方案1】:

试试这个

declare @count int
set @count = 1
while @count < 1000000
begin
    insert into #example values(rand()*10000000)
    set @count = @count +1
end

在我的机器上花了大约 35 秒。

【讨论】:

  • 你也可以去掉@r。
  • 谢谢@JimHewitt。很有用。
【解决方案2】:

1000000 行大约需要 1 秒:

CREATE TABLE #Temp (Value int)
CREATE TABLE #tb_random (Value int)

insert into #Temp
VALUES
(1),
(2),
(3),
(4),
(5),
(6),
(7),
(8),
(9),
(10)


insert into #tb_random
SELECT rand(CHECKSUM(NEWID())) * 10000000

FROM #Temp as a
CROSS JOIN #Temp as b
CROSS JOIN #Temp as c
CROSS JOIN #Temp as d
CROSS JOIN #Temp as e
CROSS JOIN #Temp as f

DROP TABLE #Temp
DROP TABLE #tb_random

为 x10 结果添加更多交叉连接。

【讨论】:

  • @BogdanSahlean 是的,你完全正确!替换为#-table
【解决方案3】:

这在我的笔记本上运行了 5 秒:

SELECT TOP 1000000 
            rn = IDENTITY(int, 1, 1), 
            random_int = ABS(CHECKSUM(NEWID())) % 1000000 + 1
INTO #random_numbers
FROM sys.all_columns AS t1
     CROSS JOIN sys.all_columns AS t2;

SELECT * FROM #random_numbers;

【讨论】:

  • 感谢 Igor 提供我的参考资料。
【解决方案4】:

那是因为你提交了每一个插入。提交意味着刷新到磁盘,因此您的脚本会......在 99% 的时间里什么都不做。它只是坐着等待磁盘刷新。分批提交:

SET NOCOUNT ON
declare @count int = 0
declare @r int;
begin transaction;
while @count <1000000
begin
  set @r = rand()*10000000;
  insert into tb_random values(@r);
  set @count += 1;
  if @count % 1000 = 0
  begin
    commit;
    begin tran;
  end
end
commit;

【讨论】:

  • 谢谢莱姆斯。我会试试的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-06
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多