2017-05-23 59 views
2

我在sql server表中有成千上萬行,其中有一行START,我需要更新表和INSERTEND行。SQL - 基於選擇行插入循環

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 
      ) 

這select返回ID的列表(而不是主鍵) 我需要循環通過每個從上述選擇的ID的,並插入到相同的表等:

​​
+2

爲什麼重新插入相同的ID?你爲什麼不執行更新? – ollie

+4

爲什麼要循環? 'INSERT到事務中SELECT distinct transaction_ID,'finished',1,2,getdate()FROM transactions' from [MSFT(Insert into select ... syntax)(https://technet.microsoft.com/en-us/library /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

我的選擇distinct是一個瘋狂的long選擇,用'not exists'它只是帶回一長串ID>?我已經更新我的問題,以顯示大的SELECT來獲得ID – user3437721

+0

@ user3437721它不應該如果你想先把它轉儲到一個臨時表中,那就好了好。 – SqlZim