SQL server--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.

Example 1.

-- Example 1. Using a trigger to display ' change a piece of data '  Use  Gocreatetrigger on infoforinsert,  Deleteasprint' changes a data 'go

Example 2.

Example 3.

--Example 3: When the fruit table changes numbers column, add data to the OrderDetails table fruit number, number change. Go Create TriggerTr_fruit_buy2 onFruit for Update,Insert,Delete as--data at the forefront of operationsDeclare @num1 intSelect @num1=Numbers fromdeleted--the data after the OperationDeclare @num2 intSelect @num2=Numbers frominserted--Poor DataDeclare @num intSet @num=@num1-@num2--Remove the fruit number from the deleted tableDeclare @code varchar( -)Select @code=Ids fromdeleted--Enter data difference and fruit number into OrderDetails tableInsert  intoOrderDetails (Ordercode,[Count])Values(@code,@num)GoSelect *  fromFruitSelect *  fromOrderDetails--Add a trigger, execute the following statement, trigger two triggers tr_fruitbuy and TR_FRUIT_BUY2 results are as followsUpdateFruitSetNumbers=Numbers-5 whereIds='k002'Select *  fromOrderDetails

Example 4

--example: Instead OF trigger, delete data of info table, first delete work and family data, and then delete info corresponding dataSelect *  fromInfoSelect *  from  Work Select *  fromFamilyGoCreate TriggerTr_person_deletet onInfoinstead of Delete as--Delete work-related data      --Remove the required delete informationDeclare @code varchar( -)Select @code=Code fromdeleted--DeleteDelete  from  Work whereInfocode=@code --Delete family related dataDelete  fromFamilywhereInfocode=@code --finally delete the related data in the Info table (the info table is the main table of the family table and the work table, before the deletion can be performed)Delete  fromInfowhereCode=@codeGo--To perform a delete after adding a triggerDelete  fromInfowhereCode='P002'

SQL server--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.