Triggers implement cascading modification of related tables in the database

Source: Internet
Author: User

Data Table relationship diagram:


The database has three tables: News, comment, news, and category. The categoryid of the news table is associated with the ID foreign key of the category table, newsid in the comment table is associated with the ID foreign key in the News table.

Run the following command in SQL:

delete from category where Id =1

If the news table and comment table have an association with ID = 1 in the category table, a message is displayed, indicating that the delete statement conflicts with the foreign key and execution fails. The trigger is used to implement cascading modification of database-related tables by solving foreign key associations.

It is easy to create a trigger in the category table to be deleted and design an SQL statement to be deleted from bottom to top:

Use [newssystem] Go/****** object: trigger [DBO]. [trigcatgorydelete] script Date: 07/26/2012 19:44:26 ******/set ansi_nulls ongoset quoted_identifier ongo -- ================ =================================-- Author: jesse -- create Date: 2012-7-26 -- Description: delete A category trigger -- ========================================== ========= alter trigger [DBO]. [trigcatgorydelete] on [DBO]. [category] instead of deleteas begin -- delete news where categoryid = (select ID from deleted) -- declare @ ID int -- select @ ID = ID from deleted -- delete news where categoryid = @ ID -- delete category where id = @ iddeclare @ caid intselect @ caid = ID from deleted -- delete comment on Delete comment where newsid in (select newsid from news wherer caid = @ CAID) -- delete news where categoryid = @ caid -- delete category where id = @ caidend




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.