简体   繁体   中英

Delete/Modify row in one table based on a condition - Oracle DBMS

I have a table structure like

 create table EMPLOYE (
    CodeEmploye varchar2(100) not null,
    NAS varchar2(100),
    CONSTRAINT employe_pk primary key (CodeEmploye)
);

create table SALAIRE (
    CodeEmploye varchar2(100) not null,
    Mois number not null,
    CONSTRAINT salaire_pk primary key (CodeEmploye, Mois),
    CONSTRAINT salaire_code_employe_fk FOREIGN KEY(CodeEmploye) REFERENCES EMPLOYE(CodeEmploye)
);

I want to add a constraint where I should not be allowed to modify/delete a row in EMPLOYE table if the same employee exist in SALAIRE table.

What is the best way to do that?

As you have define the foreign key relationship between two tables by "CodeEmployee" column, what you want has been achieved.

A little bit extension is that if you add "ON DELETE CASCADE" following the fk declaration, once you delete any row form employee table, all the related records in the salary table will be deleted as well.

One of the best ways to do is by creating a foreign key constraint on the "CodeEmploye" column during CREATE TABLE or ALTER TABLE statements. In your case, it is already created (salaire_code_employe_fk) as part of your CREATE statement. A foreign key constraint ensures that an employee row from the parent table (EMPLOYE) cannot be modified/deleted if the same employee exists in the child table (SALAIRE).

In this case, when you create the order_items table, you define a foreign key constraint with the DELETE CASCADE option as follows:

CREATE TABLE order_items   
(  
    order_id   NUMBER( 12, 0 ),   
    -- other columns  
    -- ...  
    CONSTRAINT fk_order_items_orders     
    FOREIGN KEY( order_id )     
    REFERENCES orders( order_id )   
    ON DELETE CASCADE  
);  
By doing this, whenever you delete a row from the orders table, for example:  

DELETE  
FROM  
    orders  
WHERE  
    order_id = 1;  

All the rows whose order id is 1 in the order_items table are also deleted automatically by the database system.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM