基于ID列表的SQL LOOP INSERT [英] SQL LOOP INSERT Based on List of ID's
本文介绍了基于ID列表的SQL LOOP INSERT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,我有SQL writer块.所以这是我基于伪代码要做的事情
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
}
这是我要实现的一种想法,我知道SQL中不可能使用数组,但在这里列出了它来解释我的目标.
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.
推荐答案
这就是您要的内容.
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的答案.
But if this is all you are going to do in the loop you should really use the answer from Barry instead.
这篇关于基于ID列表的SQL LOOP INSERT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文