使用SQL Cursor进行更新

时间:2015-11-24 21:16:36

标签: sql postgresql cursor psql

我的sql脚本需要帮助。

Inventory是一个包含orderunit,location,siteid和itemnum的表。此更新旨在通过以下方式更改同一项(itemnum)的所有“orderunit = NULL”:

%_TAB => %_TD 

%_TD => %_ACM 

我想用游标得到相同的结果:

UPDATE INVENTORY A 
SET A.orderunit = (SELECT B.orderunit 
                   FROM INVENTORY B 
                   WHERE B.location = A.siteid || '_TD' 
                     AND B.itemnum = A.itemnum) 
WHERE A.location = A.siteid || '_TAB' 
  AND A.orderunit IS NULL;

UPDATE INVENTORY A 
SET A.orderunit = (SELECT B.orderunit 
                   FROM INVENTORY B 
                   WHERE B.location = A.siteid || '_ACM' 
                     AND B.itemnum = A.itemnum) 
WHERE A.location = A.siteid || '_TD' 
  AND A.orderunit IS NULL;

我试图做到这一点似乎不起作用。

DECLARE
    inv_itemnum INVENTORY.itemnum%TYPE
    inv_location INVENTORY.location%TYPE
    inv_siteid INVENTORY.siteid%TYPE
    inv_orderunit INVENTORY.orderunit%TYPE

    CURSOR c_inventory_tab IS
        SELECT orderunit FROM INVENTORY WHERE location = siteid || '_TAB' AND orderunit IS NULL
        FOR UPDATE;
    CURSOR c_inventory_td IS
        SELECT orderunit FROM INVENTORY WHERE location = siteid || '_TD' AND orderunit IS NULL
        FOR UPDATE;
    CURSOR c_inventory_tabB
        SELECT orderunit FROM INVENTORY WHERE location = siteid || '_TD' AND itemnum = itemnum;
    CURSOR c_inventory_tdB
        SELECT orderunit FROM INVENTORY WHERE location = siteid || '_ACM' AND itemnum = itemnum;
BEGIN
    FOR i IN c_inventory_tab
    LOOP
    UPDATE INVENTORY
    SET orderunit = c_inventory_tabB;
    END LOOP;
END;

感谢您的帮助

0 个答案:

没有答案