How to use CURDATE() in check clause?(如何在检查子句中使用 CURDATE()?)
问题描述
我尝试创建一个表,其中dateFrom"和dateTo"字段需要高于今天的日期.所以我像这样使用CHECK
I try to create a table where 'dateFrom' and 'dateTo' fields need to be higher than today's date. So I used CHECK like this
CREATE TABLE Booking (
hotelNo int(10),
guestNo int(10),
dateFrom datetime,
dateTo datetime,
roomNo int(10),
CHECK (dateFrom >= CURDATE() AND dateTo >= CURDATE())
);
但我不断收到此错误
ERROR 1901 (HY000): Function or expression 'curdate()' cannot be used in the CHECK clause of `CONSTRAINT_1`
我在 Google 上搜索了很多次,但仍然找不到方法.
I've searched this on Google many times, but still couldn't figure out a way to do it.
推荐答案
在 MySQL 文档中,
In MySQL documentation,
允许使用文字、确定性内置函数和运算符.如果给定表中的相同数据,则函数是确定性的,多次调用产生相同的结果,独立于连接的用户.非确定性且未通过此定义的函数示例:CONNECTION_ID()、CURRENT_USER()、NOW().
Literals, deterministic built-in functions, and operators are permitted. A function is deterministic if, given the same data in tables, multiple invocations produce the same result, independently of the connected user. Examples of functions that are nondeterministic and fail this definition: CONNECTION_ID(), CURRENT_USER(), NOW().
https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
所以我改用了这样的触发器,
So I've used triggers like this instead,
CREATE TRIGGER date_check
BEFORE INSERT ON Booking
FOR EACH ROW
BEGIN
IF NEW.dateFrom <= CURDATE() OR NEW.dateTo <= CURDATE() THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Invalid date!';
END IF;
END
这篇关于如何在检查子句中使用 CURDATE()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在检查子句中使用 CURDATE()?
基础教程推荐
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
