CHECK constraint in MySQL is not working

后端 未结 8 2186
Happy的楠姐
Happy的楠姐 2020-11-21 05:15

First I created a table like

CREATE TABLE Customer (
  SD integer CHECK (SD > 0),
  Last_Name varchar (30),
  First_Name varchar(30)
);

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 05:36

    MySQL 8.0.16 is the first version that supports CHECK constraints.

    Read https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html

    If you use MySQL 8.0.15 or earlier, the MySQL Reference Manual says:

    The CHECK clause is parsed but ignored by all storage engines.

    Try a trigger...

    mysql> delimiter //
    mysql> CREATE TRIGGER trig_sd_check BEFORE INSERT ON Customer 
        -> FOR EACH ROW 
        -> BEGIN 
        -> IF NEW.SD<0 THEN 
        -> SET NEW.SD=0; 
        -> END IF; 
        -> END
        -> //
    mysql> delimiter ;
    

    Hope that helps.

提交回复
热议问题