Search code examples
oracle-databaseplsqlplsql-package

Many to Many Relationship table Not working cannot delete Value from that


declare
begin
  for i in (select aid ,address from address)
  loop
    for j in (select aid ,address from address )
    loop
      if i.address=j.address then
        if i.aid!=j.aid then
          update employee_add 
          set aid=i.aid 
          where aid=j.aid;
          delete from address 
          where aid=i.aid;
        end if;
      end if; 
    end loop;
  end loop;
end;
/

This code works fine as for loop. After that it shows error :------

*Cause: A foreign key value has no matching primary key value.
*Action: Delete the foreign key or add a matching primary key.

I have tables employee[eid (primary key) ,ename] ,address[aid (primary key),address],and many to many relation tableemployee_add[eid,aid]. Please help! Thank in Advance :)


Solution

  • You can use only one loop statement and variables( v_address and v_aid ) to make a comparison between the rows as in the block below :

    declare
      v_address address.address%type;
      v_aid     address.aid%type;  
    begin
     for i in (select aid ,address from address order by aid)
     loop  
        if nvl(v_address,'')=i.address then 
             update employee_add set aid=v_aid where aid=i.aid;  
             delete address where aid=i.aid;
        else
           v_address := i.address;
           v_aid := i.aid;   
        end if;
      end loop;
    end;