Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to delete records from two tables simultaneously

Status
Not open for further replies.

abc73

Programmer
Apr 28, 2004
89
US
Hi,
Can someone help in the sql query. I want to delete records from two tables simultaneously in Oracle.

i.e.
I have two tables A and B. I have a column that holds the same value in both the tables. Now I want to delete the records from both tables if the data in that column matches.

Thanks
 
Rockets,

By far, the fastest method for deleting matching records simultaneously from two tables is with PL/SQL:

Section 1 -- Listing of sample data:
Code:
select * from rocket1;

        ID
----------
         1
         2
         3
         5

select * from rocket2;

        ID
----------
         1
         2
         4
         5

So, if everything works as planned, we should end up with a row "3" in table rocket1 and row "4" in table rocket2.

Section 2 -- Code to delete matching rows from two tables:
Code:
begin
    for r in (select a.rowid a_id, b.rowid b_id
              from rocket1 a, rocket2 b
              where a.id = b.id) loop
        delete from rocket1 where rowid = r.a_id;
        delete from rocket2 where rowid = r.b_id;
    end loop;
end;
/

PL/SQL procedure successfully completed.

select * from rocket1;

        ID
----------
         3

1 row selected.

select * from rocket2;

        ID
----------
         4

1 row selected.

Let us know if this is what you wanted.

[santa]Mufasa
(aka Dave of Sandy, Utah, USA)
@ 16:20 (04Nov04) UTC (aka "GMT" and "Zulu"),
@ 09:20 (04Nov04) Mountain Time
 
Create a foreign-key constraint on TableB with the 'ON DELETE CASCADE' option and when you delete from TableA, it will automatically delete from TableB.


----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
That's right, LK...always choosing the easy way. [wink].

[santa]Mufasa
(aka Dave of Sandy, Utah, USA)
@ 20:31 (04Nov04) UTC (aka "GMT" and "Zulu"),
@ 13:31 (04Nov04) Mountain Time
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top