问题
With Oracle DB, is it possible to update one table and delete (matching rows) in other?
I tried various forms of MERGE
but I get either:
ORA-01446: cannot select ROWID from, or sample, a view with DISTINCT, GROUP BY, etc.
(probably caused by UNION ALL
in the view)
or
ORA-38106: MERGE not supported on join view or view with INSTEAD OF trigger.
This ("join view") suggests that specifying two tables in any form is a no-go for MERGE
. Is that correct?
(the reasons for using a single statement are: performance, consistency and clarity)
My Oracle DB is of version 11.2.
The actual problem is like this:
We (a library) have a (parent) table of books and a (child) table of content (one or zero per book, it has a FK to the books table). Every year we run a job that for each book that is older than 10 years (let's simplify the condition as it is not relevant to the problem here) we set a column named RETIRED to value "YES" in the books table and delete the row (if present) in the content table.
PS: PL/SQL solutions are welcome. (my code is in PL/SQL anyway)
回答1:
Use one transaction with two statements:
- Update
books
to retire; - Delete
content
of all the retired books.
PL/SQL solution might be:
DECLARE
TYPE id_list IS TABLE OF books.id%TYPE;
retired_list id_list;
BEGIN
UPDATE books
SET retired = 'YES'
WHERE publish_date <= add_months(TRUNC(SYSDATE), -120)
RETURNING id BULK COLLECT INTO retired_list;
FORALL id IN retired_list.FIRST .. retired_list.LAST
DELETE content
WHERE book_id = retired_list(id);
COMMIT;
END;
/
来源:https://stackoverflow.com/questions/37690394/update-and-delete-in-same-sql-in-multiple-tables