插入一个表中的多个记录带,同时环[关闭](Inserting a multiple records

2019-09-21 20:13发布

我想插入几百行成指向其他表进行PK的表。 我一直在尝试使用while循环在表中插入多条记录。 其实我建立我的测试数据。

这是我在做什么:

declare @count int;
set @count = 4018;

while @count <= 5040 
begin
    INSERT INTO [MY_TABLE]
               ([pk_from_other_table]
               ,[..]
               ,[...]
               ,[..]
               ,[..]
               ,[...]
               ,[...]
               ,[..])
        select
               (pk_from_other_table,
               ,[..]
               ,[...]
               ,[..]
               ,[..]
               ,[...]
               ,[...]
               ,[..])
    @count = @count + 1;
end

但这并不似乎工作! 谁能帮助请......所有我想要做的是记录插入数=中存在的主表中的记录数。

? 我如何能做到这一点的任何想法?

我要么得到近数不正确的语法时才

要么

消息102,级别15,状态1,第17行附近有语法错误 ''。

Answer 1:

您当前的语法问题是与@count = @count + 1; 需要被set @count = @count + 1

但...

有没有必要为一个循环。 你可以简单地做一个大的直接插入,如:

insert into your_table (fk_col, other_col1, other_col2)
select pk_col, 'something', 'something else' 
from your_other_table

如果需要,你可以添加一个where子句以上。



Answer 2:

关于消息102,级别15,状态1,第17行附近有语法错误''。

你得在第二选择列表双逗号:

select
(pk_from_other_table,
,[..]

删除一个。

关于插入:如果你要插入从源表中的所有记录到目的地多次,你能做到这一点的循环:

declare @count int;
set @count = 4018;

while @count <= 5040 
begin
    INSERT INTO DestinationTableName
               (DestinationTableColumn1Name
               ,DestinationTableColumn2Name --ect
        )
        select
               SourceTableColumn1Name
               ,SourceTableColumn2Name --ect
               from SourceTableName
    set @count = @count + 1;
end

但当你想插入来自源表中的许多行至目的地的一次, where就足够了:

INSERT INTO DestinationTableName
            (DestinationTableColumn1Name
            ,DestinationTableColumn2Name --ect
            )
            select
            SourceTableColumn1Name
           ,SourceTableColumn2Name --ect
            from SourceTableName
            where SourceTablePK between 4018 and 5040 --LowerBound and UpperBound
            --or SourceTablePK in (1, 2, 3) etc

你不必做逐列。



文章来源: Inserting a multiple records in a table with while loop [closed]