2017-05-23 14 views
2

SQLサーバーテーブルには、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のリスト(ないプライマリキー)が私は上記の選択からのIDのそれぞれをループする必要があり、同様に同じ表に挿入 :

​​
+2

なぜ同じIDを再挿入するのですか?なぜあなたは更新をしないのですか? – ollie

+4

なぜループですか? 'INSERT into transactions ... [MSFT(Select into select ...構文)](https://technet.microsoft.com/en-us/library)からSELECTトランザクションID、 '終了'、1,2、getdate()FROMトランザクション/ms189872(v=sql.105).aspx)。ループは遅いです... RDBMSのセットベースの処理はずっと効率的です。 – xQbert

答えて

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; 
+0

my select distinctは 'not exists'などでクレイジーロングセレクトです。それはちょうどIDの長いリストをもたらす>?私はidsを得るために大きなSELECTを表示するために私の質問を更新しました – user3437721

+0

@ user3437721それは一時的なテーブルに最初にそれを罰金とするよく – SqlZim

関連する問題