Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL LOOP INSERT Based on List of ID's

Hey I have SQL writers block. So here is what I'm trying to do based on pseudo-code

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
}

This is sort of the idea I'm trying to achieve, I understand that arrays are not possible in SQL but I've listed it here to explain my goal.

like image 309
Ayo Avatar asked Apr 05 '11 17:04

Ayo


2 Answers

This is what you are asking for.

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

But if this is all you are going to do in the loop you should really use the answer from Barry instead.

like image 106
Mikael Eriksson Avatar answered Oct 16 '22 00:10

Mikael Eriksson


You can just use:

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

Why would you even need to loop through each id individually

like image 26
codingbadger Avatar answered Oct 16 '22 00:10

codingbadger