SQL LOOP INSERT Based on List of ID's SQL LOOP INSERT Based on List of ID's sql sql

SQL LOOP INSERT Based on List of ID's


This is what you are asking for.

declare @IDList table (ID int)insert into @IDListSELECT idFROM table1WHERE idType = 1declare @i intselect @i = min(ID) from @IDListwhile @i is not nullbegin  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 > @iend

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


You can just use:

Insert Into Table2 (Col1, Col2, Col3)Select col1, Col2, Col3From Table1Where idType = 1

Why would you even need to loop through each id individually


INSERT INTO table2(    col1,    col2,    col3)SELECT     table1.col1,     table1.col2,     table1.col3FROM table1WHERE table1.ID IN (SELECT ID FROM table1 WHERE table1.idType = 1)