将指定数量的行插入另一个表中

时间:2016-06-08 14:29:01

标签: sql sql-server sql-server-2008 tsql

如何从另一个表中将批次或指定数量的行插入表中?

示例:从表a中将前1000行插入表b中。 然后我想将表格中的下一个1000行插入表格中,然后停止等等。

典型的陈述是:

insert into A
select top 1000 from table b

我现在如何从表格b中选择接下来的1000行? 从表b中选择前1000名

3 个答案:

答案 0 :(得分:1)

希望你有一个PK

select 1  -- to get a @@rowcount > 0
while (@@rowcount > 0)  
begin
   insert into table2 (id, val)
   select top (1000)
          table1.id, table1.val 
     from table1 
     left join table2
          on table1.id = table2.id  
    where table2.id is null 
    order by table1.id -- keep index fragmentaion down 
end

我经常使用它,效率很高 PK连接是高效的

答案 1 :(得分:0)

你可以这样做:

WITH cte AS
    (
    SELECT
        *
        ROW_NUMBER() (ORDER BY [SomeDateOrIdField]) AS 'InsertId'
    FROM
        Table
    )
INSERT INTO NewTable
SELECT
    *
FROM
    cte
WHERE
    InsertId BETWEEN 1 AND 1000

然后通过调整WHERE子句BETWEEN值重复查询下1000条记录。

答案 2 :(得分:0)

这是T-SQL中的一个循环,可以执行您想要的操作。使用您的表名和列名填写空白。

Declare @checkCount INT
Declare @loopCount INT


Set @checkCount = 1 -- This will make the loop run at least once
Set @loopCount = 0

While @checkCount > 0 -- AND @loopCount < 5
begin


    Insert into [Table2]
        (<Your column names here>)
        (Select Top 1000 <Your column names here> from Table1
          where <key> NOT IN (Select <key> from [Table2]))

    Select @checkCount = Count(*)
      from Table1
     where <key> NOT IN (Select <key> from [Table2])

    Set @loopCount = @loopCount + 1
End