Modifying Constraints
You may encounter instances where you need to update existing constraints in your SQL database. One such scenario involves adding the ON DELETE CASCADE clause to an existing foreign key constraint. This clause ensures that when a row is deleted from the parent table, the corresponding rows in the child table are also automatically deleted.
Altering Constraints
Contrary to the notion that constraints cannot be modified, you can indeed alter them by dropping the existing constraint and recreating it with the desired modifications. To illustrate this process, consider the constraint ACTIVEPROG_FKEY1 on the ACTIVEPROG table:
CONSTRAINT ACTIVEPROG_FKEY1 FOREIGN KEY(ActiveProgCode) REFERENCES PROGRAM(ActiveProgCode),
To add the ON DELETE CASCADE clause to this constraint, follow these steps:
Drop the Existing Constraint:
ALTER TABLE ACTIVEPROG DROP CONSTRAINT ACTIVEPROG_FKEY1;
Recreate the Constraint with the Desired Modification:
ALTER TABLE ACTIVEPROG ADD CONSTRAINT ACTIVEPROG_FKEY1 FOREIGN KEY(ActiveProgCode) REFERENCES PROGRAM(ActiveProgCode) ON DELETE CASCADE;
By following these steps, you successfully altered the constraint to include the ON DELETE CASCADE clause, ensuring that when records are deleted from the PROGRAM table, the corresponding records in the ACTIVEPROG table are automatically removed.
The above is the detailed content of How Can I Modify Existing SQL Constraints, Such as Adding ON DELETE CASCADE?. For more information, please follow other related articles on the PHP Chinese website!