SQL LOOP INSERT基于ID列表

Ayo*_*Ayo 11 sql t-sql loops sql-server-2005 insert

嘿,我有SQL编写器块.所以这就是我想要基于伪代码做的事情

int[] ids = SELECT id FROM (table1) WHERE idType = 1 -> Selecting a bunch of record ids to work with
FOR(int i = 0; i <= ids.Count(); ++i) -> loop through based on number of records retrieved
{
    INSERT INTO (table2)[col1,col2,col3] SELECT col1, col2, col3 FROM (table1)
    WHERE col1 = ids[i].Value AND idType = 1 -> Inserting into table based on one of the ids in the array

    // More inserts based on Array ID's here
}
Run Code Online (Sandbox Code Playgroud)

这是我想要实现的想法,我理解数组在SQL中是不可能的,但我在这里列出来解释我的目标.

Mik*_*son 22

这就是你要求的.

declare @IDList table (ID int)

insert into @IDList
SELECT id
FROM table1
WHERE idType = 1

declare @i int
select @i = min(ID) from @IDList
while @i is not null
begin
  INSERT INTO table2(col1,col2,col3) 
  SELECT col1, col2, col3
  FROM table1
  WHERE col1 = @i AND idType = 1

  select @i = min(ID) from @IDList where ID > @i
end
Run Code Online (Sandbox Code Playgroud)

但如果这就是你要在循环中做的全部,你应该真的使用Barry的答案.


cod*_*ger 8

你可以使用:

Insert Into Table2 (Col1, Col2, Col3)
Select col1, Col2, Col3
From Table1
Where idType = 1
Run Code Online (Sandbox Code Playgroud)

为什么你甚至需要单独遍历每个id


Dus*_*ine 7

INSERT INTO table2
(
    col1,
    col2,
    col3
)
SELECT 
    table1.col1, 
    table1.col2, 
    table1.col3
FROM table1
WHERE table1.ID IN (SELECT ID FROM table1 WHERE table1.idType = 1)
Run Code Online (Sandbox Code Playgroud)

  • 为什么要打扰`IN`?为什么不只是`WHERE table1.idType = 1` (2认同)