我需要在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多个小时。你能给我一个解决这个性能问题的想法吗?
答案 0 :(得分:4)
试试这个
declare @count int
set @count = 1
while @count < 1000000
begin
insert into #example values(rand()*10000000)
set @count = @count +1
end
我的机器上花了大约35秒。
答案 1 :(得分:2)
这是因为你提交了每个插入内容。提交意味着刷新到磁盘,因此您的脚本在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;
答案 2 :(得分:1)
我的笔记本电脑在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;
答案 3 :(得分:1)
Stacked CTEs是快速生成1.000.000行的最佳解决方案之一。接下来,如果你必须生成介于1和1.000.000之间的随机数,那么我将使用以下表达式:1 + ABS(CHECKSUM(NEWID())) % 1000000
。请注意,此脚本可以生成相同的&#34;随机&#34;价值两倍或更多。
;WITH e1(n) AS
(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b), -- 10*10
e3(n) AS (SELECT 1 FROM e1 CROSS JOIN e2 AS b), -- 10*100
e4(n) AS (SELECT 1 FROM e3 CROSS JOIN e3 AS b) -- 1000*1000
INSERT dbo.TargetTable(RandValue)
SELECT 1 + ABS(CHECKSUM(NEWID())) % 1000000 AS RandValue
--or INTO #TempTable
FROM e4;
注意#1:我认为这是一次性任务。
注意#2:要生成随机值,也可以使用CRYPT_GEN_RANDOM。
答案 4 :(得分:0)
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结果添加更多交叉连接。