【备注】基于 LLM 和开源文档 RAG 的论坛小助手已开放测试,在发帖时输入 [@论坛小助手] 即可召唤小助手,欢迎试用!
obclient(root@sys)[EcommerceSys]> create table test1( CD date default current_date );
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your OceanBase version for the right syntax to use near ‘current_date )’ at line 1
[172.17.0.2:2882] [2025-04-08 02:11:09.946587] [YB42AC110002-0006323ACF03AFBE-0-0]
obclient(root@sys)[(none)]> create table test1( CD date default (current_date) );
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your OceanBase version for the right syntax to use near ‘(current_date) )’ at line 1
不行
CREATE TABLE test1 (
CD DATETIME DEFAULT SYSDATE
);
此方法会将当前的日期和时间作为默认值插入到字段中。
方法二:通过触发器实现默认值为当前日期
如果您必须使用 DATE 类型,并且希望默认值为当前日期,可以通过创建触发器来实现:
CREATE TABLE test1 (
CD DATE
);
DELIMITER $$
CREATE TRIGGER set_current_date
BEFORE INSERT ON test1
FOR EACH ROW
BEGIN
IF NEW.CD IS NULL THEN
SET NEW.CD = CURRENT_DATE;
END IF;
END$$
DELIMITER ;