2015-12-07 137 views
1

我創建了一個表安排與檢查約束:SQL CHECK約束正確

mysql> create table schedule(order_date date, dely_date date 
          check(dely_date>order_date)); 
Query OK, 0 rows affected (0.50 sec) 

當我插入違反檢查約束,SQL報告沒有錯誤的值。

mysql> insert into schedule values('2015-11-20','2014-12-25'); 
Query OK, 1 row affected (0.10 sec) 

mysql> select * from schedule; 
+------------+------------+ 
| order_date | dely_date | 
+------------+------------+ 
| 2015-11-20 | 2014-12-25 | 
+------------+------------+ 
1 row in set (0.00 sec) 

我已經在order_date之前插入了dely_date。

回答

1

MySQLCHECK約束作爲工作CHECKJakub Kania's answer

例使用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

您可以使用觸發器做驗證:

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

+0

謝謝。但爲什麼沒有觸發器就不能工作? – user3297764

+0

@ user3297764因爲MySQL沒有實現'CHECK'語法。它只是佔位符。 – lad2025

2

哦,它工作正常。按照manual

的CHECK子句是解析但忽略所有的存儲引擎

你可能想嘗試一個數據庫是多了幾分理智。

+1

我喜歡'sane' :)你應該提到的是一個解決辦法是使用觸發器。 [Sane數據庫示例](https://data.stackexchange.com/stackoverflow/query/404686)+您需要在「CHECK」之前使用comman。 – lad2025

+0

對不起。我不明白。 – user3297764

+0

我該怎麼做才能讓sql報告錯誤? – user3297764