如何在单个命令中在表中插入n个记录

时间:2012-02-28 10:58:27

标签: sql-server-2005 bulkinsert

我想在表中插入10000条记录,我目前正在编写此代码 在sql server 2005中

declare @n decimal(10,0);
set @n = 0;
while ( @n < 10000)
begin
   insert into table1 values (@n+1)
   set @n = @n + 1
end

在上面的代码插入命令执行10000次是否存在任何单个命令。

3 个答案:

答案 0 :(得分:5)

您也可以使用sys对象:

INSERT INTO table1(n)
SELECT TOP 10000 ROW_NUMBER() OVER(ORDER BY a.object_id) AS n FROM sys.objects a CROSS JOIN sys.objects b
GO

答案 1 :(得分:4)

您可以使用CTE创建一个包含10000个项目的内存表,并使用此表格插入到您的实际表格中。

;WITH q (n) AS (
   SELECT 1
   UNION ALL
   SELECT n + 1
   FROM   q
   WHERE  n < 10000
)
INSERT INTO table1 
SELECT * FROM q
OPTION (MAXRECURSION 0)

答案 2 :(得分:0)

快速方式(来自HERE):

declare @t table (number int)
insert into @t 
    select 0
    union all
    select 1
    union all
    select 2
    union all
    select 3
    union all
    select 4
    union all
    select 5
    union all
    select 6
    union all
    select 7
    union all
    select 8
    union all
    select 9

insert into numbers
    select
        t1.number + t2.number*10 + t3.number*100
    from
        @t as t1, 
        @t as t2,
        @t as t3