回答

收藏

基于ID列表的SQL LOOP INSERT

技术问答 技术问答 117 人阅读 | 0 人回复 | 2023-09-13

嘿,我有SQL writer块。所以这就是我基于伪代码要做的。
- k$ J2 k& T$ {' ]  @int[] ids = SELECT id FROM (table1) WHERE idType = 1 -> Selecting a bunch of record ids to work withFOR(int i = 0; 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数组不能用,但这里列出了解释我的目标。
, Q# r6 m2 }  p  G                                                               
# {1 m+ X' k& W$ i    解决方案:                                                               
. ]  ^& {% X: T4 N: k                                                                这就是你想要的。
8 V' [6 _) m' B* C3 xdeclare @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但是,如果您想在循环中完成所有操作,则应重用Barry的答案。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则