The below mentioned procedure is intended to:
- fetch jobids from cp_work_card which exist in cpTemplateWorkCard
- Fetch the first record of bhours for the jobid from the cp_work_card
- update the same to cpTemplateworkCard
Hwoever, all the rows of cpTemplateworkCard are updated with the value of bHours found in last row. But, the values in the variable are stored correctly while execution
DECLARE
jobId VARCHAR2(30);
bHours float;
idx NUMBER(4,0);
CURSOR c1
IS
select distinct
cp.job_id
from cp_work_card cp,
cptemplateworkcard temp
where cp.job_id = temp.JOBID;
BEGIN
idx:=1;
DBMS_OUTPUT.PUT_LINE('id : jobId : bHours');
OPEN c1;
LOOP
FETCH c1 INTO jobId;
EXIT WHEN C1%NOTFOUND;
select cpw.BUDGET_HOUR
into bHours
from cp_work_card cpw
where cpw.job_id=jobId
AND rownum<2;
/*DBMS_OUTPUT.PUT_LINE('Budget Hours: '||bHours);
UPDATE TO CPTEMPLATE*/
UPDATE cptemplateworkcard tmpCard
SET tmpCard.BUDGET_HOUR=bHours
where tmpCard.JOBID=jobId;
DBMS_OUTPUT.PUT_LINE(idx || ' : ' || jobId || ' : ' || bHours);
idx:= idx+1;
END LOOP;
CLOSE c1;
END;
Couldn’t you achieve the same with a single SQL update statement?
I haven’t tested this but the principle is the same…
EDIT: Given your constraints and if you must use a procedure then could you not:
EDIT:
FYI, your current procedure isn’t working because you have named your variable holding the job ID as
jobIdwhich also happens to be the name of a column in the tablecptemplateworkcard. Therefore when you perform your update it defaults to thinking yourWHEREclause is comparing the table column with itself thereby updating every row with whatever the value ofbHoursis. When the procedure has finished, obviously the last value ofbHourswhat the final value returned from the cursor hence you are seeing all the values in the table set to this final value.If you rename your
jobIdvariable to something likev_jobidthen it should solve the problem.Hope it helps…
If the only constraint is that it must be in a PL/SQL procedureal block then this will be the most efficient procedure: