使用while循环在表中插入多个记录

sim*_*ula -5 sql t-sql sql-server

我想在表中插入几百行,指向其他表中的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
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用!任何人都可以帮忙...我想要做的就是插入记录数=主表中存在的记录数.

?关于如何实现这个目标的任何想法?

我要么接近计数不正确的sytax

要么

消息102,级别15,状态1,行17'','附近的语法不正确.

Kla*_*sen 13

您当前的语法问题是@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
Run Code Online (Sandbox Code Playgroud)

如果需要,可以where在上面添加一个子句.

  • 您正在基于集合的环境中工作 - 如果可能,请避免循环. (8认同)
  • @ user1630846 - 到目前为止,几百行并不是很多记录. (3认同)
  • @ user1630846请参阅:[RBAR](https://www.google.com/webhp?sourceid=chrome-instant&ie=UTF-8&ion=1#hl=en&sclient=psy-ab&q=rbar+row+agonizing+row&oq=RBAR+行+ gs_l = hp.3.1.0i30l2.235416.709443.0.711007.30.24.4.1.1.1.312.3682.5j14j4j1.24.0.les%3B..0.0 ... 1c.d1S7a2ITybE&PBX = 1&BAV = on.2,or.r_gc.r_pw .r_cp.r_qf.&FP = fe97cc68227e2ceb&离子= 1&BIW = 1489&波黑= 897) (3认同)
  • @ user1630846循环很慢,在使用关系数据库时应尽可能避免. (2认同)

Pio*_*raj 7

关于消息102,级别15,状态1,行17','附近的语法不正确.:

你在第二个选择列表中有双重逗号:

select
(pk_from_other_table,
,[..]
Run Code Online (Sandbox Code Playgroud)

删除一个.

关于插入:如果要将源表中的所有记录多次插入目标,可以循环执行:

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
Run Code Online (Sandbox Code Playgroud)

但是当你想要从源表到目的地插入许多行时,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
Run Code Online (Sandbox Code Playgroud)

您不必逐行执行此操作.