trigger in sql

This article is written in combination with <Classification and Differences of Database Triggers> written by a great god, and some examples, etc., are all taken from this article!!!

1. What is a trigger

                 Trigger is a method provided by SQL server to programmers and data analysts to ensure data integrity. It is a special stored procedure related to table events. Its execution is not invoked by a program or manually started. , but is triggered by events. For example, when an operation is performed on a table (insert, delete, update), it will be activated to execute, and the query has no trigger. Triggers are often used to enforce data integrity constraints and business rules. Of course, we need to know that the stored procedure has no return value (return), while the trigger has (return),

2. What can triggers do

       Triggers can query other tables and can contain complex SQL statements. They are mainly used to enforce compliance with complex business rules or requirements. For example: you can control whether new orders are allowed to be inserted based on the customer's current account status. This is the answer of Baidu Encyclopedia. I don't understand it. Then I think the trigger is like an event in javaScript, whether it is a click event or a mouse move in and out. Set up, when he executes the start of these events according to a certain behavior (here is the trigger), with the trigger, we can completely execute the first sql statement, and the trigger also executes the second statement (of course here The classification of triggers is involved)

Third, the classification of triggers   

DDL triggers

       It is a new trigger of Sql Server 2005, which is mainly used to audit and standardize operations on tables, triggers, views and other structures in the database. For example, in modifying tables, modifying columns, adding new tables, adding new columns, etc. It is executed when the database structure changes. We mainly use it to record the modification process of the database, and to limit the modification of the database by programmers, such as not allowing to delete certain specified tables.

 DML triggers

         When the data in the table in the database changes, including any operations of insert, update and delete, if we write the corresponding DML trigger to the table, the trigger will be executed automatically. The main role of DML triggers is to enforce business rules, as well as extend Sql Server constraints, default values, etc. Because we know that constraints can only constrain data in the same table, and triggers can execute arbitrary Sql commands.      

Example: Create a trigger, when the employee table deletes a record, add the deleted record to the delete log table

 Alternative triggers

INSTEAD OF triggers, also known as substitute triggers, are used to perform an alternate action in place of the action that triggered
the . For example: an INSTEAD OF trigger for an INSERT event, which is triggered by an INSERT statement. When an INSERT
statement occurs, the statement will not be executed, but the statement defined in the INSTEAD OF trigger will be executed.
Creating an INSTEAD OF trigger requires the following points: it
                 can only be created on a view, and the view does not specify the WITH CHECK OPTION option.
                 The BEFORE or AFTER options cannot be specified. The FOR EACH ROW sub is optional, that is, an INSTEAD OF trigger can only fire at the row level, or can only be a row-level trigger, and it is not necessary to specify.
                 It is not necessary to create an INSTEAD OF trigger on a view against a table, just create a DML trigger.

System event triggers:                           

            Login trigger:

                          Example: Create login, exit triggers

Fourth, the ultimate effect of triggers

          Data can be forced to be validated or converted before being written to the data table.

          When an error occurs in the trigger, the result of the transaction will be undone.

           Some database management systems can use triggers for Data Definition Language (DDL), called DDL triggers.

            The instruction of the change (INSTEAD OF) can be replaced according to the specific situation.

5. Application of triggers

       1. Ensure the security of the database

User actions can be restricted based on time, such as not allowing modification of database data after hours and holidays.
User actions can be restricted based on data in the database, such as not allowing prices to rise more than 10% at a time.

       2. Implement complex security authorizations

Using triggers to control the security of entities, you can lend permissions to various database values.

       3. Provide complex auditing functions

Audit the statements of users operating the database.
Write user updates to the database to the audit table.

       4. Maintain synchronization tables between different databases

Snapshots can be used to replicate data between different databases, but some systems require
real-time , and triggers must be used to replicate data from one database to another.

        5. Implement complex data integrity rules

Implement non-standard data integrity checks and constraints. Triggers can create more complex constraints than rules.
Unlike rules , triggers can reference columns or database objects.
Provides a variable default value.

        6. Implement complex non-standard database-related integrity rules

Triggers can serially update related tables in the database. For example, a
delete can cause a corresponding deletion of matching rows in other tables.
 Triggers can reject or roll back changes that violate the integrity of the correlation, canceling transactions attempting to update data.
This trigger works when a foreign key is inserted that does not match its primary key.

6. The composition of the trigger

 The trigger is made by

Trigger events (such as CRUD).

Trigger time (i.e. before or after CRUD occurs).

Trigger action (the purpose and intent after the TRIGGER is triggered),

Trigger objects (including tables, views, schemas, databases. Only when a trigger event that meets the trigger conditions occurs on these objects, the trigger action will be executed.).

Trigger condition (A logical expression is specified by the WHEN clause. Only when the value of the expression is TRUE, the trigger will be automatically executed when the trigger event is encountered, causing it to perform the triggering action.).

Trigger frequency (indicates the number of times the action defined in the trigger is executed. That is, the statement-level (STATEMENT)
trigger and the row-level (ROW) trigger.)

7. Trigger sequence of triggers

  1. Execute BEFORE statement-level triggers;

2 For each row affected by the statement
   2.1 Execute BEFORE row-level triggers
   2.2 Execute DML statements
   2.3 Execute AFTER row-level triggers
3. Execute AFTER statement-level triggers

8. Advantages of flip-flops

Advantage: Triggers can cascade changes through related tables in the database, but these changes can be more efficiently executed by cascading referential integrity
constraints . Triggers can enforce more complex constraints than those defined with CHECK
constraints . Unlike CHECK constraints, triggers can reference columns in other tables. For example, a trigger can use
a table to compare inserted or updated data, and to perform other operations such as modifying data or displaying user-
defined error messages. Triggers can also evaluate the state of the table before and after data modification and take countermeasures based on the difference. Multiple triggers of
the allow multiple different countermeasures to be taken in response to the same
modify statement.

Disadvantages: Triggers are powerful and can easily and reliably implement many complex functions, but they also have some disadvantages, that
is , the maintenance of databases and applications will be difficult due to our abuse. In database operations, we can implement data operations through
relationships , triggers, stored procedures, applications, etc. At the same time, rules, constraints, and default values ​​are also important guarantees to ensure
data integrity. If we rely too much on triggers, it will inevitably affect the structure of the database and increase
the complexity of maintenance procedures.

Nine. Notes on writing triggers

First of all, the trigger does not accept parameters,

Secondly, there can be up to 12 triggers on a table, but at the same time, the same event, there can only be one trigger of the same type, and there can be no contradiction between the triggers.

Of course, the more triggers in a table, the greater the performance impact of DML operations on the table. The maximum trigger size is 32kb.

If it is really necessary, you can create the procedure first, and then use the call statement in the trigger to call,

Only DML statements can be used in the execution part of the trigger, DDL statements cannot be used

The trigger cannot contain transaction control statements, because the trigger is part of the trigger statement, the trigger statement is committed, and the trigger is also committed or rolled back when the trigger is rolled back.

Any procedures, functions, and functions that are called in the body of a trigger cannot use transaction control statements.

No long blob variables can be declared in the trigger body, and the new value new and old value oid cannot be added to any long and blob columns in the table

The syntax format and function of different types of triggers are quite different

Triggers declare variable value-added methods similar to dephi, use := symbol to assign value, new value new, old value old don't forget: quotation mark.

Guess you like

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