SQL LOOP INSERT基于ID列表

时间:2011-04-05 17:20:54

标签: sql sql-server-2005 tsql loops 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
}

这是我想要实现的想法,我理解在SQL中不可能使用数组,但我在此处列出了它来解释我的目标。

3 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:8)

你可以使用:

Insert Into Table2 (Col1, Col2, Col3)
Select col1, Col2, Col3
From Table1
Where idType = 1

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

答案 2 :(得分: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)