SQL - 基于选择行插入循环

时间:2017-05-23 15:47:40

标签: sql-server

我在sql server表中有数千行,其中有START行,我需要更新表格,INSERT每行END行。

 select  distinct transaction_id from transactions t1
      where
        this_status_id = 2 and that_type_id = 1
              and not exists
              (
              select  *
              from    transactions t2
              where   t2.transaction_id = t1.transaction_id
                      and t2.this_status_id in (1,3,4)
                      and t2.that_type_id = 1
              )

此选择返回ID列表(不是主键) 我需要从上面的select中循环遍历每个id,然后INSERT到同一个表中,如:

INSERT INTO transactions VALUES (@transaction_id, "finished", 1, 2, GETDATE())

1 个答案:

答案 0 :(得分:3)

为什么在你可以的时候循环:

insert into transactions
select distinct transaction_id, 'finished', 1, 2, getdate()
from transactions
where this_status_id = 2 
  and that_type_id = 1
  and not exists (
    select  1
    from  transactions t2
    where t2.transaction_id = t1.transaction_id
      and t2.this_status_id in (1,3,4)
      and t2.that_type_id = 1
  );

使用临时表:

select distinct transaction_id 
into #TempTable
from transactions t1
where this_status_id = 2 
  and that_type_id = 1
  and not exists (
    select  1
    from  transactions t2
    where t2.transaction_id = t1.transaction_id
      and t2.this_status_id in (1,3,4)
      and t2.that_type_id = 1
  );

insert into transactions
distinct transaction_id, 'finished', 1, 2, getdate()
from #TempTable;