使用一组(x,y)值生成和填充表的最快方法

时间:2013-04-30 17:04:04

标签: sql-server-2008 tsql

我正在尝试将100,000,000个基于简单坐标的记录插入表中。有没有比下面的t-sql命令更快的方法来实现这一点

declare @x int
declare @y int
set @x = 0
set @y = 0

begin tran
while @x < 10000
begin
    while @y < 10000
    begin
        insert into world (x,y) VALUES (@x,@y)
        set @y = @y + 1
    end
    set @y = 0
    set @x = @x + 1
end
commit tran

4 个答案:

答案 0 :(得分:3)

如果您有号码表,请使用您自己的号码表。否则,您可以使用如下的spt_values。

WITH base_num AS
(SELECT number FROM master..spt_values WHERE type = 'P' AND number < 100)
, num AS 
(SELECT b1.number * 100 + b2.number AS number
 FROM base_num b1
 CROSS JOIN base_num b2
) 
INSERT INTO world (x,y)
SELECT n1.number AS x, n2.number AS y 
FROM num n1
CROSS JOIN num n2

答案 1 :(得分:2)

这样的东西可能会有效,如果100毫米的行对于服务器而言并不是太大了 - 它显然取决于日志文件的大小和速度。

WITH counter AS 
(SELECT TOP 10000 ROW_NUMBER() 
   OVER (ORDER BY a.[object_id], a.name, b.[object_id]) AS rownum 
   FROM sys.columns a, sys.columns b) 
INSERT INTO World (x,y) 
SELECT a.rownum, b.rownum 
  FROM counter a, counter b

答案 2 :(得分:2)

您可以使用数字表

 SELECT TOP 10000 -- use a smaller value for testing, this will take a bit
        IDENTITY(INT,1,1) as N
   INTO #Numbers
   FROM Master.dbo.SysColumns sc1,
        Master.dbo.SysColumns sc2

然后像

SELECT
    n1.N as 'N1'
    , n2.N as 'N2'
INTO #values
FROM #Numbers n1
    CROSS JOIN #Numbers n2


SELECT COUNT(*) FROM #values

要获得集合的笛卡尔,只要您可以使用简化的坐标值。

答案 3 :(得分:2)

如果您没有数字表,可以使用CTE模拟一个:

with cte as
(select 1 i union all select i+1 i from cte where i < 10000)
INSERT into World (x,y) 
SELECT x.i, y.i 
from cte x cross join cte y
option (maxrecursion 0)