Cascade delete for sql tables

We can use cascade delete on property for deleting data from child tables. With cascade delete on, the corresponding data gets deleted from the child table when the data from the parent table gets deleted. This saves a lot of time writing the code for deleting data from child tables. Also it can overall improve your application’s performance.

Illustration:-

parenttable

Deleting data with parentid=2 from the parent table (see above) will result in deletion of corresponding data from the child table(see below). This deletion will be handled automatically by the sql server.

childtable

You can add the cascade delete on property to the child table by this method:-

alter table tblchild 

add constraint fk_parentchild foreign key (parentidFK) references tblparent(parentid)

on delete cascade;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: