基于ID列表的SQL LOOP INSERT

前端之家收集整理的这篇文章主要介绍了基于ID列表的SQL LOOP 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,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中是不可能的,但我在这里列出来解释我的目标.

解决方法

这是你要求的.
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,col3) 
  SELECT col1,col3
  FROM table1
  WHERE col1 = @i AND idType = 1

  select @i = min(ID) from @IDList where ID > @i
end

但是如果这是你在循环中所做的一切,你应该真正地使用Barry的答案.

原文链接:https://www.f2er.com/mssql/75156.html

猜你在找的MsSQL相关文章