Create and delete a MySQL command line trigger

Source: Internet
Author: User

Example:

Existing tables tab1 and tab2

The trigger must have the following functions

When you insert a record to tab1, tab2 also inserts the same record.

 
Mysql> delimiter // mysql> Create trigger t_afterinsert_on_tab1-> after insert on tab1-> for each row-> begin-> insert into tab2 (tab2_id) values (New. tab1_id);-> end;-> //
 
Execute the following statement to restore the settings.
 
Mysql> delimiter;

The role of Delimiter is to tell the MySQL interpreter whether the command has been completed and whether MySQL can be executed.By default, Delimiter is a semicolon ;. In the command line client, if a command line ends with a semicolon,After you press enter, MySQL will execute this command. But sometimes, you don't want MySQL to do this.The statement contains a semicolon. Use delimiter //,In this way, the MySQL interpreter will execute this statement only when // appears.You can also create a trigger using batch processing.

 
Create trigger t_afterinsert_on_tab1after insert on tab1for each rowbegin insert into tab2 (tab2_id) values (New. tab1_id); end;

Save the preceding content as an SQL FileRun it. Note that Delimiter is also used to change the statement end mark.Delete trigger:

 
Drop trigger t_afterinsert_on_tab1;

Why do I use for each row when creating a trigger? This is because when this sentence is added, the trigger event is Row-level. Therefore, an event must be triggered for each row.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.