2013-05-01 29 views
0

我想你的幫助使存儲過程來更新庫存表。 起初,我將所有的賬單項存儲在一張臨時表中,然後一旦保存就會從庫存表中扣除庫存,然後將其存儲在Bill_Item表中,並且Temp_Bill_Item表將被刪除。我怎樣才能在sql表中循環

enter image description here

回答

2

無論是臨時表,也不遊標是必需的這一點:

update stock_table 
    set qty = qty - bi.qty 
from stock_table st 
    join bill_items bi 
    on bi.item_id = st.item_id 
    and bi.itemcode = st.itemcode; 

這假設每個項目是隻出現一次在bill_items表。如果你可以有相同的itemid/itemcode多行你需要一個稍微不同的說法:

update stock_table 
    set qty = qty - bi.total_qty 
from stock_table st 
    join (select item_id, itemcode, sum(qty) as total_qty 
     from bill_items 
     group by item_id, itemcode 
) bi 
    on bi.item_id = st.item_id 
    and bi.itemcode = st.itemcode; 

(語法沒有測試過,你沒有張貼樣本數據一起玩)