如何使用我的学生表预防将来的日期?

时间:2017-04-23 19:05:15

标签: mysql triggers



-- Create a trigger that will prevent  an update to a student table if EnrolledDate is in the future

USE College ;

DROP TRIGGER IF EXISTS  Student_Before_Update; 

DELIMITER $$

        CREATE TRIGGER Student_Before_Update
        BEFORE UPDATE ON Student 
        FOR EACH ROW 
        
      BEGIN 
      
	IF NEW.EnrolledDate > '2016-10-18'  THEN 
				 SIGNAL SQLSTATE VALUE '45000'
				  SET MESSAGE_TEXT= 'Enrolled date may not be in the future';
		END IF; 

      END $$

DELIMITER ;

UPDATE Student
SET EnrolledDate= DATE(now())
WHERE ID= 1; 

UPDATE Student
SET EnrolledDate= DATE_ADD(now(),INTERVAL 1 DAY)
WHERE ID=1; 




大家好,

我正在创建一个应该显示错误的BEFORE UPDATE触发器 如果我更新学生未来约会的注册日期,则会显示该消息。例如,学生表中最后一次插入的注册日期是' 2016-04-17',因此该日期之后的任何其他记录都应标记一条错误消息,说明"注册日期可能不会在将来"我已经在这方面工作了几个小时,但我还是没有得到。有人可以帮帮我吗?到目前为止,这是我的代码。

1 个答案:

答案 0 :(得分:0)

试试这个:

-- Create a trigger that will prevent  an update to a student table if EnrolledDate is in the future

USE College ;

DROP TRIGGER IF EXISTS  Student_Before_Update; 

DELIMITER $$

CREATE TRIGGER Student_Before_Update
BEFORE UPDATE ON Student 
FOR EACH ROW 

BEGIN 

    IF DATE_FORMAT(NEW.EnrolledDate,'%Y-%m-%d') > DATE_FORMAT(NOW(),'%Y-%m-%d')  THEN 
        SIGNAL SQLSTATE VALUE '45000'
        SET MESSAGE_TEXT= 'Enrolled date may not be in the future';
    END IF; 

END $$

DELIMITER ;

UPDATE Student
SET EnrolledDate= DATE(now())
WHERE ID= 1; 

UPDATE Student
SET EnrolledDate= DATE_ADD(now(),INTERVAL 1 DAY)
WHERE ID=1;