SQL Server (eight)--triggers

Source: Internet
Author: User

A trigger is a special kind of stored procedure that executes automatically when a table Update,insert or DELETE statement is executed, with no parameters and no return value;

First, trigger type

1. For Trigger

Triggered after an action is executed (the code in the trigger executes after the deletion is completed), the for trigger cannot be specified for the view, and the trigger can be specified only for the table.

2. Instead OF trigger

Can be understood as an alternative to triggering the execution, after writing this, write the execution code is useless, the trigger code is covered by the

Second, create a trigger

Create trigger Insert_student-- naming conventions

On student-- for which table

For insert-- to which action to trigger

As

Code snippet to trigger execution

Go

For example:

Create Trigger Delete_info  on  ofdeleteas    gocreatetrigger  Delete_ Nation onforDeleteas Go    
View Code

NOTE: Triggers are commonly used for cascading deletions:

Create Trigger Delete_student
On student
Instead of delete
As

-- If you want to delete student table data, you need to cascade delete
DECLARE @sno varchar (20);
Set @sno = Sno from deleted--deleted fixed format, in order to delete the data that can be deleted, do not delete, but show them, in this get the data to be deleted Sno, and then first delete the other table in this SNO data
Delete from score where Sno = @sno;
Delete from student where Sno = @sno;

Go

For example:

Create TriggerDelete_info onInfoinstead of Delete as    Declare @c varchar( -)    Select @c =Code fromdeletedDelete  from  Work whereInfocode=@c    Delete  fromFamilywhereInfocode=@c    Delete  fromInfowhereCode=@cGo
View Code

SQL Server (eight)--triggers

Related Article

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.