sql CHECK constraint not working properly [duplicate]

落花浮王杯 提交于 2019-12-02 03:19:24
Lukasz Szozda

The CHECK constraint in MySQL is ignored as in Jakub Kania's answer

Example of working CHECK using SQL Server:

create table #schedule(order_date date,
dely_date date,
check(dely_date>order_date));

insert into #schedule values('2015-11-20','2014-12-25');
-- The INSERT statement conflicted with the CHECK constraint "CK_#schedule_A59B8DED". 
-- The conflict occurred in database "tempdb", table "dbo.#schedule___
-- __________________00000000C9D8". The statement has been terminated.

INSERT INTO #schedule values('2015-12-24','2015-12-25');

SELECT *
FROM #schedule;

LiveDemo

You can use trigger to do validation:

CREATE TABLE `schedule`(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
                        order_date DATETIME,
                        dely_date DATETIME);              

CREATE TRIGGER `schedule_trg_ins` BEFORE INSERT ON `schedule`
FOR EACH ROW
BEGIN
    IF NOT(New.dely_date>New.order_date) THEN
    SIGNAL SQLSTATE '10000'
        SET MESSAGE_TEXT = 'check constraint on schedule failed during insert';
    END IF;
END;

CREATE TRIGGER `schedule_trg_upd` BEFORE UPDATE ON `schedule`
FOR EACH ROW
BEGIN
    IF NOT(New.dely_date>New.order_date) THEN
    SIGNAL SQLSTATE '10000'
        SET MESSAGE_TEXT = 'check constraint on schedule failed during update';
    END IF;
END;

INSERT INTO `schedule`(order_date, dely_date)
VALUES ('2015-12-24','2015-12-25');

INSERT INTO `schedule`(order_date, dely_date)
VALUES ('2015-12-26','2015-12-25');
-- check constraint on schedule failed during insert

UPDATE `schedule`
SET order_date = '2015-12-26'
WHERE id = 1;
-- check constraint on schedule failed during update

SqlFiddleDemo

Oh, it is working properly. According to the manual:

The CHECK clause is parsed but ignored by all storage engines

You may want to try a db that is a little more sane.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!