trigger

trigger

  It is a special kind of stored procedure. The general stored procedure is called directly through the stored procedure name, and the trigger is mainly

  Triggered by events (addition, deletion, modification) and executed. It is automatically enforced when the data in the table changes.

  There are two common triggers: after (for), instead of, for insert, update, delete events.

  after(for) means that after the code is executed, the trigger is executed

  instead of means to replace your action with the already written trigger before executing the code

 

Trigger syntax:

  create trigger trigger name on action table

  for|after         instead of

  update|insert|delete

  as

  SQL statement

 

Trigger Implementation Schematic

 

Trigger Example

Example1

 

--Prohibit user from inserting data (actually insert first, then delete it right away!)

 

  create trigger tr_insert on bank

 

  for --for indicates the operation after the execution

 

  insert -- that is, the insert operation is performed first, and the inserted record is saved in the temporary table

 

  as

 

   --After executing the insert, delete the record just inserted in the newly generated table,

 

   --The id of the record just inserted at this time is obtained through the temporary table inserted

 

  delete * from bank where cid=(select cid from inserted)

 

 

 

  After the above trigger is generated, when the user enters the insert statement again, the effect will not be seen!

 

  Such as: insert into bank values ​​('0004', 10000), is not inserted into the database.

 

Example2

-- Add 10 yuan to the account of anyone who deletes it

  create trigger tr_dalete on bank

  instead of

  delete

  as

  update bank balance=balance+10 where cid=(select cid from deleted)

  After the trigger is generated, when the user enters the delete statement, the corresponding id is not only not deleted, but his account is increased by 10 yuan

 

  For example: delete from bank where cid='0002', after executing this sentence, the account numbered 0002 will increase by 10 yuan

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325022935&siteId=291194637