加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

基于ID列表的SQL LOOP INSERT

发布时间:2020-12-12 08:51:42 所属栏目:MsSql教程 来源:网络整理
导读:嘿我有SQL编写器阻止.所以这里是我正在做的基于伪代码 int[] ids = SELECT id FROM (table1) WHERE idType = 1 - Selecting a bunch of record ids to work withFOR(int i = 0; i = ids.Count(); ++i) - loop through based on number of records retrieved{
嘿我有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的答案.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读