Cascade deletion with triggers

Source: Internet
Author: User

This problem occurs when the table is deleted in cascade mode. An error occurs when a primary key information is deleted. Because there are foreign key information, a trigger is used to delete all the information.
 
<Span style = "font-family: Microsoft YaHei; font-size: 16px; color: # 6600cc;"> create trigger trigCategoryDelete (create trigger)
ON Category (ON which table to create)
After DELETE (trigger event)
AS
BEGIN
Delete news where caID = (select id from deleted) (some processing statements triggered by the trigger)
END
</Span>

However, after is after the delete operation, an error is returned. The delete operation is complete. How can I delete a foreign key.
Instead of replaces the delete statement:
 
<Span style = "font-family: Microsoft YaHei; font-size: 16px; color: # 6600cc;"> alter trigger [dbo]. [trigCategoryDelete]
ON [dbo]. [category]
Instead of DELETE
AS
BEGIN
Declare @ id int
Select @ id = id from deleted
-- Delete news
Delete news where caId = @ id
-- Delete a news category
Delete category where id = @ id
END </span>
In this way, the information in the foreign key can be deleted.
Cascade deletion of three tables
 
<Span style = "font-family: Microsoft YaHei; font-size: 16px; color: # 6600cc;"> alter trigger [dbo]. [trigCategoryDelete]
ON [dbo]. [category]
Instead of DELETE
AS
BEGIN
Declare @ caId int
Select @ caId = id from deleted
-- Delete comment
Delete comment where newsId = (select id from news where caId = @ caId)
-- Delete news
Delete news where caId = @ caId
-- Delete a news category
Delete category where id = @ caId
END </span>

 
In this case, an error will be reported, and the error will correspond to multiple comments in a piece of news. The solution is to change "=" to "in", so that all comments can be deleted.
Ps: as for the names of the logtail and tables in the front, we believe most people know that when the trigger is saved and then opened, the table information will be automatically completed.

Author: lixueru0819

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.