A trigger is a special kind of stored procedure that cannot be called explicitly and is automatically activated only when an INSERT, UPDATE, delete operation is made to a table. So triggers can be used to implement complex integrity constraints on a table.
SQL Server creates two dedicated tables for each trigger: the inserted table and the deleted table. These two tables are maintained by the system, and they exist in memory rather than in the database. The structure of the two tables is always the same as the structure of the table to which the trigger is executed, and the two tables associated with the trigger are also deleted when the trigger is completed.
Operations on a table |
Inserted logic table |
Deleted logic Table |
Add record (insert) |
Storage of Added Records |
No |
Delete a record (delete) |
No |
To store deleted records |
Modify record (update) |
Storage of updated records |
Store pre-update records |
TRAPS: Update triggers are only triggered once by update, regardless of the number of records updated
Alter TRIGGERDbo.tmp_table1_update onTmp_table1 AfterUPDATE as SELECT * into#INS fromINSERTEDDECLARE @PersonCode VARCHAR( -),@Amount Money IF UPDATE(Amount)BEGIN DECLAREAmountcursorCURSOR for SELECTPersoncode,amount from#INSOPENAmountcursorFETCH NEXT fromAmountcursor into @PersonCode,@Amount while @ @FETCH_STATUS=0 BEGIN UPDATETmp_table2SETAmount=@Amount WHEREPersoncode=@PersonCode FETCH NEXT fromAmountcursor into @PersonCode,@Amount END CLOSEAmountcursordeallocateAmountcursorEND
Traps exist for triggers