[英]Oracle procedure to update values of one table to another another table field
[英]Oracle Pl/SQL procedure to update values of one table to another
我在這里的要求是我有兩個具有兩個屬性的表。我編寫了一個程序,它應該從table1獲取值(sor_ID)並在表2中根據主鍵更新它。
Table 1
-------
Primary Key | Sor_ID
AAA | 100
BBB | 200
Table 2
-----
Foreign Key | Sor_ID
AAA | NULL
BBB | NULL
create or replace
Procedure UPDDATE_SORID_2
IS
s_id VARCHAR2(256 byte);
CURSOR C1 IS
SELECT A.SOR_INSTRMNT_ID
FROM TEST_TABLE B,TEMP_SOR_ID A
where A.INSTRMNT_KEY=B.INSTRMNT_KEY;
BEGIN
open c1;
loop
fetch c1 into s_id;
update TEST_TABLE set SOR_INSTRMNT_ID=S_ID;
commit;
end LOOP;
close c1;
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20001,'An error was encountered - '
||SQLCODE||' -ERROR'||SQLERRM);
end;
即使在運行數小時后,此過程也不會返回任何更新。 請建議
你不需要游標就可以做到這一點。
如果表之間有外鍵關系,則可以在連接的兩個表的密鑰保留視圖上更新。
一般模式是:
Update (
select parent_table.key parent_key,
child_table.key child_key,
parent_table.value parent_value,
child_table.value child_value
from parent_table
join child_table on child_table.key = parent_table.key)
set
child_value = parent_value;
這比基於PL / SQL游標的方法更快,更健壯。
順便提一下,您還可以使用類似的刪除密鑰保留視圖的技術刪除子記錄。
當然,這並不能解答為什么要在父表中放置父屬性的問題。
我注意到你的手術有幾個問題。
1)它永遠運行,因為你的循環沒有EXIT。
2)您的update語句每次都會更新整個表,因為您沒有使用WHERE子句。
我建議你修改如下:
CREATE OR REPLACE PROCEDURE upddate_sorid_2
IS
s_id VARCHAR2(256 byte);
s_instrmnt_key VARCHAR2(256 byte);
CURSOR c1 IS
SELECT a.sor_instrmnt_id, a.instrmnt_key
FROM test_table b,temp_sor_id a
WHERE a.instrmnt_key = b.instrmnt_key;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO s_id, s_instrmnt_key;
EXIT WHEN c1%NOTFOUND;
UPDATE test_table
SET sor_instrmnt_id = s_id
WHERE INSTRMNT_KEY = s_instrmnt_key;
END LOOP;
CLOSE c1;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20001,'An error was encountered - '
||SQLCODE||' -ERROR'||SQLERRM);
end;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.