Home > Database > Mysql Tutorial > How Can I Prevent MySQL Inserts Based on a Condition Using Triggers?

How Can I Prevent MySQL Inserts Based on a Condition Using Triggers?

Patricia Arquette
Release: 2025-01-16 18:40:11
Original
223 people have browsed it

How Can I Prevent MySQL Inserts Based on a Condition Using Triggers?

Preventing MySQL INSERTS with a Trigger

To prevent inserting a row when a specific condition is met, such as a birthdate set in the future, you can create a trigger. Here's how:

CREATE TRIGGER foo BEFORE INSERT ON table
FOR EACH ROW
BEGIN
  IF NEW.birthdate > CURRENT_DATE() THEN
    SIGNAL SQLSTATE '45000';
  END IF;
END;
Copy after login

Canceling the Insert

To cancel the insert within the trigger, use the SIGNAL SQLSTATE syntax. For example, to raise an error when the birthdate is in the future, you would use:

SIGNAL SQLSTATE '45000';
Copy after login

This will throw an unhandled user-defined exception and prevent the insertion.

The above is the detailed content of How Can I Prevent MySQL Inserts Based on a Condition Using Triggers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template