The creation and use of mysql triggers

    **What is a Trigger?** A trigger (TRIGGER) is one of the database objects in MySQL, introduced since version 5.0.2. It functions similarly to functions in programming languages, requiring declaration and execution. However, unlike regular functions, triggers are not called directly by programs or manually; instead, they are automatically activated by specific database events. Think of it as an event listener in web development, where actions like inserting, updating, or deleting data can trigger predefined operations. Why use triggers? In real-world applications, you often encounter scenarios where certain actions need to be performed automatically when data changes. For example: - When adding a student to a table, the total number of students should update accordingly. - When inserting new student records, validations for phone numbers or emails may be required. Triggers handle these tasks automatically. They are executed when specific SQL statements—such as INSERT, UPDATE, or DELETE—are triggered. Other SQL commands do not activate them. ![The creation and use of MySQL triggers](http://i.bosscdn.com/blog/27/49/55/5-1G2261R333V2.png) **MySQL Overview** MySQL is a relational database management system developed by MySQL AB in Sweden and now owned by Oracle. It's one of the most popular RDBMS systems, especially for web applications. MySQL organizes data into multiple tables rather than storing everything in a single repository, which improves performance and flexibility. It uses SQL (Structured Query Language), the standard language for interacting with databases. MySQL offers both a community and a commercial version. Due to its lightweight nature, fast performance, and open-source availability, it’s widely used for small and medium-sized websites. Thanks to its strong community support, MySQL pairs well with PHP and Apache to create a powerful web development stack. **Creating Triggers** To create a trigger, you can use the following syntax: ```sql CREATE [DEFINER = { user | CURRENT_USER }] TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_body ``` - `trigger_name`: A unique name for the trigger. - `trigger_time`: Either `BEFORE` or `AFTER`, indicating when the trigger fires relative to the event. - `trigger_event`: The event that activates the trigger: `INSERT`, `UPDATE`, or `DELETE`. - `tbl_name`: The table on which the trigger operates. - `trigger_body`: The SQL statements to execute when the trigger is fired. **Creating a Simple Trigger** Example: Create a trigger to automatically update the student count when inserting or deleting records. 1. **Prepare the tables:** ```sql CREATE TABLE student_info ( stu_no INT(11) NOT NULL AUTO_INCREMENT, stu_name VARCHAR(255), PRIMARY KEY (stu_no) ); CREATE TABLE student_count ( student_count INT(11) DEFAULT 0 ); INSERT INTO student_count VALUES (0); ``` 2. **Create the triggers:** ```sql CREATE TRIGGER trigger_student_count_insert AFTER INSERT ON student_info FOR EACH ROW UPDATE student_count SET student_count = student_count + 1; CREATE TRIGGER trigger_student_count_delete AFTER DELETE ON student_info FOR EACH ROW UPDATE student_count SET student_count = student_count - 1; ``` 3. **Test the triggers:** ```sql INSERT INTO student_info VALUES (NULL, 'Zhang Ming'), (NULL, 'Li Ming'), (NULL, 'Wang Ming'); SELECT * FROM student_count; -- Result: 3 DELETE FROM student_info WHERE stu_name IN ('Zhang Ming', 'Li Ming'); SELECT * FROM student_count; -- Result: 1 ``` **Creating a Trigger with Multiple Statements** If your trigger needs to perform multiple actions, wrap the code in `BEGIN...END`. Example: Track student counts per class. 1. **Update the tables:** ```sql ALTER TABLE student_info ADD COLUMN student_class INT; CREATE TABLE student_count ( student_count INT(11), student_class INT ); INSERT INTO student_count VALUES (0, 0), (0, 1), (0, 2); ``` 2. **Create the trigger:** ```sql DELIMITER $$ CREATE TRIGGER trigger_student_count_insert AFTER INSERT ON student_info FOR EACH ROW BEGIN UPDATE student_count SET student_count = student_count + 1 WHERE student_class = 0; UPDATE student_count SET student_count = student_count + 1 WHERE student_class = NEW.student_class; END $$ DELIMITER ; ``` 3. **Insert and test:** ```sql INSERT INTO student_info VALUES (NULL, 'AAA', 1), (NULL, 'BBB', 1), (NULL, 'CCC', 2); SELECT * FROM student_count; -- Result: Total 3, Class 1 has 2, Class 2 has 1 ``` **Understanding NEW and OLD Keywords** In triggers, `NEW` refers to the new row being inserted, while `OLD` refers to the row being deleted. These keywords allow you to access values from the current or previous state of the data. **Trigger Usage Restrictions** - Triggers can only be created on permanent tables, not temporary ones. - They cannot call stored procedures that return values or use dynamic SQL. - Triggers cannot start or end transactions, but using `SAVEPOINT` is allowed. - Foreign key operations do not trigger triggers. - Triggers on slave tables are not activated during statement-based replication. - Triggers cannot have a `RETURN` statement; use `LEAVE` to exit early. **Exception Handling in Triggers** Triggers follow a sequence: `BEFORE`, then the operation, then `AFTER`. If any step fails, the entire operation is rolled back (for transactional tables), but not for non-transactional ones. **Viewing Triggers** You can view all triggers using `SHOW TRIGGERS`, or query the `information_schema.triggers` table for more precise results. **Deleting a Trigger** To remove a trigger, use: ```sql DROP TRIGGER trigger_name; ``` Triggers are powerful tools for automating database logic, improving consistency, and reducing manual intervention. Understanding their behavior and limitations is essential for effective database design.

    Loudspeaker

    We engineer loudspeaker solutions that offer great durability, quality sound, and peak performance. When an electrical signal is applied to the voice coil it generates a magnetic field. The voice coil and magnets within the Speaker interact causing the coil and attached cone to move, generating sound. Our loudspeakers incorporate large magnets and particular voice coils to handle a broad range of frequencies and sounds. Additionally, our loudspeakers can be configured in multiple cone materials, sizes, shapes and gaskets to adapt to different operational environments. We have provided loudspeaker solutions for both indoor and outdoor applications. Our loudspeaker designs can be found in home theater systems and on the handlebars of some of the most exquisite motorcycles.

    Lond Speaker,Lead Wire Speaker,Waterproof Loudspeaker,Micro Waterproof Speaker

    Jiangsu Huawha Electronices Co.,Ltd , https://www.hnbuzzer.com

    Previous Post: The creation and use of mysql triggers
    Next Post: What is the difference between theodolite and the total station?
    Home
    Recent Posts
    • Lockheed analyzes space data with NEC's AI s…
    • Lockheed analyzes space data with NEC's AI s…
    • AI return to commercial nature is the key to app…
    • AI return to commercial nature is the key to app…
    • Sik Vision Technology Controls Collaborative Rob…
    • Sik Vision Technology Controls Collaborative Rob…
    • The creation and use of mysql triggers
    • The creation and use of mysql triggers
    • What is the difference between theodolite and th…
    • Hangzhou Intelligent "Troika" Enabling…
    • Hangzhou Intelligent "Troika" Enabling…
    • Design and Implementation of Cascade Control of …
    • How to manage users through user groups and acce…
    • How to manage users through user groups and acce…
    • The precious chip save environment
    • The precious chip save environment
    • What are the types of SOP packages? What are the…
    • What are the types of SOP packages? What are the…
    • TCL LE32D59 installs third-party applications vi…
    • TCL LE32D59 installs third-party applications vi…