there is no need to add any sproc or any trigger for this situation , if you use constraints for your table .. If you use foreign key constraint with ON DELETE CASCADE , it will automatically delete all the referenced records in the referenced table ..
As you have said that you did it manually that shows how poorly your table is designed.
I will show it using two example table -
1. t1 has an 'id' and a 'name' column
2. t2 has 'id' and 'phone' column , t1.id is the foreign key for this table ..
CREATE TABLE t1
(
id int NOT NULL,
name varchar(30)
)
go
CREATE TABLE t2
(
id int,
phone varchar(12),
CONSTRAINT fk_1 FOREIGN KEY (id) REFERENCES t1(id) ON DELETE CASCADE)
go
Now if you try to delete data from t1 which is referenced to t2 , it will delete all such refernces.
Now say we have following data
t1
id name
----------
1 Som
2 Manu
t2
id phone
-----------
1 78787878
1 76777666
2 76776677
and then we have executed following
DELETE FROM t1 WHERE id=1
go
it will delete 1 record from t1 and two records from t2 (which are referenced)
There may be one more situation, where you dont want to delete data from t1 which is referenced. In such situation just dont use ON DELETE CASCADE , use only FOREIGN KEY constraint , it will give error if any such data is deleted which has references in other table.
|