Triggers are often used SqlServer syntax AFTER, INSTEAD OF and Detailed

Create a simple flip-flop

TRIGGER trigger_name the CREATE 
 ON table_name 
 [the WITH the ENCRYPTION] 
  the FOR | an AFTER | INSTEAD OF [DELETE, INSERT, UPDATE] 
 AS 
  T-SQL statements 
GO 

trigger position: database> table> I have here is the table name table_name> Trigger

explanation:
1, [ WITH eNCRYPTION]: indicates the flip-encryption, encrypted trigger execution method can not be viewed

when [dELETE, iNSERT, uPDATE] corresponds to when the delete, insert, update, three actions are triggered
When performing insert, insert data acquisition, can select * from inserted to read 
when performing delete, to obtain data before deletion, can be read select * from deleted
when executing update, to obtain data before the update, available select * from deleted read take, after acquiring the updated data, the read select * from inserted available


2, AFTER: after a successful operation (here after insertion table_a), the trigger operation performed
e.g.
CREATE TRIGGER T_A
ON table_a
after insert
as
begin

declare @id int,@name varchar(20)
select @id=id,@name=name from inserted
insert into table_b values(@id,@name)

end


3, INSTEAD OF: The trigger only "fuse" databases, the triggers can be executed to the desired results, needs to be judged by the trigger logic, because the trigger is often accompanied by a lot of judgment branch.
For example,
the CREATE TRIGGER T_B
the ON table_a
INSTEAD of INSERT
AS
the begin

the IF EXISTS (SELECT * from table_a WHERE name = (SELECT name from inserted The))
ROLLBACK TRANSACTION
the PRINT 'the name already exists in'

the ELSE
the INSERT the INTO table_a the VALUES (SELECT * from inserted The)
the PRINT ' insert success'

End

Guess you like

Origin www.cnblogs.com/jijm123/p/11597359.html