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
Patricia ArquetteOriginal
2025-01-16 18:40:11225browse

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;

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';

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!

Statement:
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