SQLServer trigger _ MySQL

Source: Internet
Author: User
A trigger is a special type of stored procedure. The difference between a trigger and a stored procedure: a trigger is triggered by an event and executed automatically. a stored procedure can be called by the name of the stored procedure. A trigger is a special type of stored procedure when a table is inserted, updated, or deleted.

The difference between a trigger and a stored procedure: a trigger is triggered by an event and executed automatically. a stored procedure can be called by the name of the stored procedure.

What is a trigger?

A special stored procedure that is automatically executed when a trigger inserts, updates, or deletes a table. Triggers are generally used for constraints with more complex check constraints. The difference between a trigger and a Common Stored procedure is that a trigger is used to operate a table. For example, update, insert, and delete operations, the system automatically calls the trigger for executing the table. In SQL Server 2005, triggers can be divided into two types: DML triggers and DDL triggers. DDL triggers affect the execution of multiple data definition language statements, including create, alter, and drop statements.

DML triggers are divided:

1. after trigger (triggered later)

A. insert trigger

B. update trigger

C. delete trigger

2. instead of trigger (previously triggered)

The after trigger requires that the trigger be triggered only after an insert, update, or delete operation is executed and can only be defined on the table. The instead of trigger does not execute the defined operations (insert, update, delete) but only executes the trigger itself. You can either define an instead of trigger on a table or a View.

The trigger has two special tables: the insert table and the delete table ). These two tables are logical tables and virtual tables. Two tables created by the system in the memory are not stored in the database. Both tables are read-only and can only read data but cannot modify data. The results of these two tables are always the same as the structure of the table applied by the modified trigger. After the trigger is complete, the two tables will be deleted. The data in the Inserted table is the Inserted or modified data, and the data in the deleted table is the data before or after the update.

Table operations

Inserted logical table

Deleted logical table

Insert)

Store added Records

None

Delete)

None

Store deleted records

Update)

Store updated records

Store records before update

When updating data, you delete the table record and add a record. In this way, the inserted and deleted tables have updated data records. Note: the trigger itself is a transaction, so you can perform some special checks on the modified data in the trigger. If not, you can use transaction rollback to cancel the operation.

Create a trigger

[Syntax]

Create trigger tgr_nameon table_namewith encrypion-encryption trigger for update... as Transact-SQL # Create an insert trigger -- create an insert trigger if (object_id ('tgr _ classes_insert ', 'tr') isnotnull) droptrigger tgr_classes_insertgocreate trigger tgr_classes_inserton classesfor insert -- insert trigger as -- define the variable declare @ id int, @ name varchar (20), @ temp int; -- query the inserted records in the inserted table. select @ id = id, @ name = name from inserted; set @ name = @ na Me + convert (varchar, @ id); set @ temp = @ id/2; insert into student values (@ name, 18 + @ id, @ temp, @ id ); print 'student added successfully! '; Go -- insert data into classes values ('5ban', getDate (); -- query data select * from classes; select * from student orderby id;

Insert trigger. a newly inserted record is added to the inserted table.

# Create a delete trigger -- delete trigger if (object_id ('tgr _ classes_delete ', 'tr') isnotnull) droptrigger tgr_classes_deletegocreate trigger tgr_classes_deleteon classesfordelete -- delete trigger as print ...... '; If (object_id ('classesbackup', 'u') isnotnull) -- classesBackup exists, insert data directly into classesBackup select name, createDate from deleted; else -- no classesBackup is created, and then select * into classesBackup from deleted; print 'is successfully inserted! '; Go -- do not display the number of affected rows -- set nocount on; delete classes where name = '5ban'; -- query data select * from classes; select * from classesBackup;

The delete trigger will save the deleted data in the deleted table when deleting the data.

# Create an update trigger -- update a trigger of the update type if (object_id ('tgr _ classes_update ', 'tr') isnotnull) droptrigger resume trigger resume classesforupdateas declare @ oldName varchar (20 ), @ newName varchar (20); -- select @ oldName = name from deleted; if (exists (select * from student where name like '%' + @ oldName + '%') begin -- select @ newName = name from inserted; update stu Dent set name = replace (name, @ oldName, @ newName) where name like '%' + @ oldName + '%'; print 'Cascade data modification successful! '; End else print' no need to modify the student table! '; Go -- query data select * from student orderby id; select * from classes; update classes set name = 'five class' where name = 'five class ';

After the update trigger updates the data, it saves the pre-update data in the deleted table and the updated data in the inserted table.

# Update a column-level trigger if (object_id ('tgr _ classes_update_column ', 'tr') isnotnull) droptrigger triggers trigger tgr_classes_update_columnon classesforupdateas -- Column-level trigger: whether the class creation time is updated. if (update (createDate) begin raisError ('system prompt: the class creation time cannot be modified! ', 16, 11); rollbacktran; endgo -- test select * from student orderby id; select * from classes; update classes set createDate = getDate () where id = 3; update classes set name = 'four class' where id = 7;

You can use update to determine whether to update column records;

# Instead of type trigger

The instead of trigger indicates that the operation defined by the trigger is not executed (insert, update, delete), but only the content of the trigger itself.

Create syntax

Create trigger tgr_nameon table_namewith encryptioninstead ofupdate... asT-SQL # Create An instead of trigger if (object_id ('tgr _ classes_inteadOf ', 'tr') isnotnull) drop trigger triggers trigger tgr_classes_inteadOfon classesinstead ofdelete/*, update, insert */as declare @ id int, @ name varchar (20); -- query the information to be deleted, assign the select @ id = id, @ name = name from deleted; print 'Id: '+ convert (varchar, @ id) +', Name: '+ @ name; -- delete the student information first. delete student where cid = @ id; -- delete the classes Information. delete classes where id = @ id; print 'the message [id: '+ convert (varchar, @ id) +', name: '+ @ name +'] is deleted successfully! '; Go -- testselect * from student orderby id; select * from classes; delete classes where id = 7; # display custom message raiserrorif (object_id ('tgr _ message ', 'tr') isnotnull) drop trigger tgr_messagegocreate trigger tgr_messageon studentafter insert, updateasraisError ('tgr _ message trigger triggered ', 16, 10 ); go -- testinsert into student values ('Lily', 22, 1, 7); update student set sex = 0 where name = 'Lucy '; select * from student orderby id; # Modify the trigger alter trigger tgr_messageon studentafter deleteasraisError ('tgr _ message trigger triggered ', 16, 10); go -- testdeletefrom student where name = 'Lucy '; # enable and disable triggers -- disable the trigger disable trigger tgr_message on student; -- enable the trigger enable trigger tgr_message on student; # query the created trigger information -- query the existing trigger select * from sys. triggers; select * from sys. objects where type = 'tr'; -- view the trigger event select te. * from sys. trigger_events te join sys. triggers ton t. object_id = te. object_idwhere t. parent_class = 0 and t. name = 'tgr _ valid_data '; -- view the create trigger statement exec sp_helptext 'tgr _ message'; # Example to verify if (object_id ('tgr _ valid_data ', 'tr') isnotnull) droptrigger tgr_valid_1_ocreatetrigger tgr_valid_dataon studentafter insertasdeclare @ age int, @ name varchar (20); select @ name = s. name, @ age = s. age from inserted s; if (@ age <18) beginraisError ('Age when new data is inserted has a problem ', 16, 1); rollbacktran; endgo -- testinsert into student values ('Forest ', 2, 0, 7); insert into student values ('Forest', 22, 0, 7 ); select * from student orderby id; # Example, operation log if (object_id ('log', 'u') isnotnull) droptable loggocreatetable log (id intidentity (1, 1) primarykey, actionvarchar (20), createDate datetime default getDate () goif (exists (select * from sys. objects where name = 'tgr _ student_log ') droptrigger tgr_student_loggocreatetrigger tgr_student_logon studentafter insert, update, deleteasif (exists (select 1 from inserted )) and (exists (select 1 from deleted) begininsert into log (action) values ('updated'); endelseif (exists (select 1 from inserted) andnotexists (select 1 from deleted) begininsert into log (action) values ('inserted'); endelseif (notexists (select 1 from inserted) andexists (select 1 from deleted )) begininsert into log (action) values ('deleted'); endgo -- testinsert into student values ('king', 22, 1, 7 ); update student set sex = 0 where name = 'King'; delete student where name = 'King'; select * from log; select * from student orderby id;

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.