My requirment here is i have two tables with two attributes.I have written a procedure which should take values(sor_ID) from table1 and update it in Table 2 based on primary key.
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;
This procedure returns nothing updated even after hours of running it. Kindly suggest
You do not need cursors to do this.
If you have a foreign key relationship between the tables you can update on a key-preserved view of the two tables joined.
The general pattern would be:
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;
This will be faster and more robust than a PL/SQL cursor-based method.
Incidentally, you can also delete child records using a similar technique of deleting against a key-preserved view.
Of course this does not answer the question of why you'd want to place a parent attribute in a child table.
I noticed a couple of problems with your procedure.
1) It runs forever because there is no EXIT from your loop.
2) Your update statement updates the whole table every time because you are not using a WHERE clause.
I recommend you alter as follows:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.