Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于ID列表的SQL循环插入_Sql_Sql Server 2005_Tsql_Loops_Insert - Fatal编程技术网

基于ID列表的SQL循环插入

基于ID列表的SQL循环插入,sql,sql-server-2005,tsql,loops,insert,Sql,Sql Server 2005,Tsql,Loops,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 (tab

嘿,我有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, 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中是不可能的,但我在这里列出了它来解释我的目标。

您可以使用:

INSERT INTO table2
(
    col1,
    col2,
    col3
)
SELECT 
    table1.col1, 
    table1.col2, 
    table1.col3
FROM table1
WHERE table1.ID IN (SELECT ID FROM table1 WHERE table1.idType = 1)
Insert Into Table2 (Col1, Col2, Col3)
Select col1, Col2, Col3
From Table1
Where idType = 1

为什么您甚至需要逐个循环检查每个id这就是您所要求的

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的答案。

您使用的是什么DBMS?T-SQL的答案将不同于mySQL的答案。为什么还要麻烦使用IN呢?为什么不只是在table1.idType=1的情况下?如果假设必须从table1以外的其他表中提取col2值,那么如何对该查询进行处理?如果输入id并将其用作in语句中的副本,它将只计算每个id的值一次。例如:选择SoldProducts的总价,其中spid在1,2,3,4,5,1,3,5中,它将输出与以下相同的结果:选择SoldProducts的总价,其中spid在1,2,3,4,5中。对不起,我不想让我的问题变得冗长和复杂,但循环中会有其他基于id的插入。@Ayo:通过不在问题,实际上延迟了你得到你需要的答案。只要所需的逻辑仍然存在,伪代码就可以了。无论如何,@Mikael提供的答案应该是您需要的。