Home Database Mysql Tutorial mysql trigger usage example sharing

mysql trigger usage example sharing

Jan 17, 2018 am 10:06 AM
mysql share trigger

This article mainly introduces the relevant information about the detailed explanation of mysql trigger usage examples. Friends who need it can refer to it. I hope it can help everyone.

Detailed explanation of MySQL trigger syntax:

The trigger is a special stored procedure that inserts (inset), deletes (delete) or modifies (update) a specific table. Execution is triggered when the data in it is executed, and it has more refined and complex data control capabilities than the standard functions of the data itself. Triggers are not called by a program, but are triggered by an event. Automatically enforce business rules when data is modified, often used to strengthen data integrity constraints and business rules. Triggers can query other tables and contain replicated SQL statements. Triggers can also be used to enforce referential integrity. Triggers can enforce more complex constraints than those defined with check constraints.

(1).CREATE TRIGGER syntax

CREATE TRIGGER trigger_nametrigger_time trigger_event ON tbl_name FOR EACH ROW trigger_stmt;
The trigger is a named database object related to the table. This object is activated when a specific event occurs on the table.
The trigger is related to the table named tbl_name. tbl_name must refer to a permanent table. A trigger cannot be associated with a TEMPORARY table or view.
                    Trigger_time is the action time of the trigger program. It can be BEFORE or AFTER to indicate whether the trigger is fired before or after the statement that activates it.
         trigger_event specifies the type of statement that activates the trigger program. trigger_event can be one of the following values:

(1).INSERT: The trigger is activated when a new row is inserted into the table, for example, through INSERT, LOAD DATA and REPLACE
statements.
(2).UPDATE: The trigger is activated when a row is changed, for example, through the UPDATE statement.
        (3).DELETE: The trigger is activated when a row is deleted from the table, for example, through the DELETE and REPLACE statements.

It is important to note that trigger_event is not very similar to the SQL statement that activates the trigger program through table operations. For example, the BEFORE trigger on INSERT can be activated not only by the INSERT statement, but also by the LOAD DATA statement. One example that may cause confusion is INSERT INTO .. ​​ON DUPLICATE UPDATE ... Syntax: BEFORE INSERT trigger will activate for each row, followed by AFTER INSERT trigger, or BEFORE UPDATE and AFTER UPDATE trigger, depending Are there duplicate keys on the row.

There cannot be two triggers for a given table with the same trigger action time and event. For example, for a certain table, there cannot be two BEFORE UPDATE triggers. But there can be 1 BEFORE UPDATE trigger and 1 BEFORE INSERT trigger, or 1 BEFOREUPDATE trigger and 1 AFTER UPDATE trigger. trigger_stmt is the statement executed when the trigger is activated. If you plan to execute multiple statements, use the BEGIN ... END compound statement structure. In this way, you can use the same statements allowed in stored subprograms

(2).DROP TRIGGER syntax

DROP TRIGGER[schema_name.]trigger_name discards the trigger program. The schema name (schema_name) is optional. If schema is omitted, the trigger will be discarded from the current schema.

Note: When upgrading from a MySQL version before MySQL 5.0.10 to 5.0.10 or later (including all MySQL 5.1 versions), all triggers must be discarded before upgrading. and recreate them later, otherwise, DROP TRIGGER does not work after upgrade. The DROP TRIGGER statement requires SUPER permission.

(3). Using trigger programs

In this section, we introduce the method of using trigger programs in MySQL 5.1 and introduce the use of trigger programs. limits.

A trigger is a named database object associated with a table that is activated when a specific event occurs on the table. In some trigger usages, it can be used to check values ​​inserted into a table, or to perform calculations on values ​​involved in an update.

The trigger program is related to the table. When an INSERT, DELETE or UPDATE statement is executed on the table, the trigger program will be activated. Triggers can be set to activate before or after a statement is executed. For example, a trigger can be activated before each row is deleted from the table, or after each row is updated. To create a trigger or discard a trigger, use the CREATE TRIGGER or DROP TRIGGER statement. A trigger cannot call a stored procedure that returns data to the client, nor can it use dynamic SQL using the CALL statement (which allows stored procedures to return data to the trigger through parameters). program).

            Triggers cannot use statements that explicitly or implicitly start or end transactions, such as START TRANSACTION,
COMMIT, or ROLLBACK.

Use the OLD and NEW keywords to access the columns in the rows affected by the trigger (OLD and NEW are not case-sensitive).

In the INSERT trigger program, only NEW.col_name can be used, no old rows. In a DELETE trigger, only OLD.col_name can be used, no new lines. In the UPDATE trigger, you can use OLD.col_name to refer to a column in a row before the update, or NEW.col_name to refer to a column in the updated row.

Columns named with OLD are read-only. You can reference it, but not change it. For columns named with NEW, you can reference it if you have SELECT permission. In the BEFORE trigger program, if you have UPDATE permission, you can use "SET NEW.col_name = value" to change its value. This means that you can use triggers to change values ​​that will be inserted into new rows, or to update values ​​in rows. In the BEFORE trigger program, the NEW value of the AUTO_INCREMENT column is 0, which is not the sequence number that will be automatically generated when a new record is actually inserted.

By using the BEGIN...END structure, you can define a trigger program that executes multiple statements. In the BEGIN block, you can also use other syntax allowed in stored subroutines, such as conditions and loops. However, just like stored subprograms, when defining a trigger program that executes multiple statements, if you use the MySQL program to enter the trigger program, you need to redefine the statement separator so that you can use the character ";" in the trigger program definition. In the example below, these points are demonstrated. In this example, an UPDATE trigger is defined that checks for the new value that will be used when updating each row and changes the value so that it is in the range of 0 to 100. It must be a BEFORE trigger because the value needs to be checked before it is used to update the row:

mysql> delimiter //
mysql> CREATE TRIGGER upd_check BEFORE UPDATE ON account
   -> FOR EACH ROW
   -> BEGIN
   -> IF NEW.amount < 0 THEN
   -> SET NEW.amount = 0;
   -> ELSEIF NEW.amount > 100 THEN
   -> SET NEW.amount = 100;
   -> END IF;
   -> END;//
mysql> delimiter ;
Copy after login

It is simpler to define the stored procedure separately and then use a simple The CALL statement calls a stored procedure from the triggering procedure. This method is also helpful if you plan to call the same subroutine from within several trigger programs. During the execution of the trigger program, MySQL handles errors as follows:

(1) If the BEFORE trigger program fails, the operation on the corresponding line will not be executed.
(2) The AFTER trigger is executed only if the BEFORE trigger (if any) and the row operation have been successfully executed.
(3) If an error occurs during the execution of the BEFORE or AFTER trigger program, it will cause the entire statement that calls the trigger program to fail.
(4) For transactional tables, if the trigger program fails (and the resulting failure of the entire statement), all changes performed by the statement will be rolled back. For non-transactional tables, this type of rollback cannot be performed, so even if the statement fails, any changes made before the failure are still valid.

Example 1:

mysql> CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));
mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account FOR EACH ROW SET @sum = @sum + NEW.amount;
Copy after login

Related recommendations:

##Mysql triggers are used for information backup in PHP projects. Restoration and clearing

Questions about MySQL triggers

Introduction to mysql triggers and how to create and delete triggers

The above is the detailed content of mysql trigger usage example sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

How to create a new connection to mysql in navicat How to create a new connection to mysql in navicat Apr 09, 2025 am 07:21 AM

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

How to recover data after SQL deletes rows How to recover data after SQL deletes rows Apr 09, 2025 pm 12:21 PM

Recovering deleted rows directly from the database is usually impossible unless there is a backup or transaction rollback mechanism. Key point: Transaction rollback: Execute ROLLBACK before the transaction is committed to recover data. Backup: Regular backup of the database can be used to quickly restore data. Database snapshot: You can create a read-only copy of the database and restore the data after the data is deleted accidentally. Use DELETE statement with caution: Check the conditions carefully to avoid accidentally deleting data. Use the WHERE clause: explicitly specify the data to be deleted. Use the test environment: Test before performing a DELETE operation.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

See all articles