MySQL DATE field with default CURDATE(). NOT DATETIME

a 夏天 提交于 2019-11-28 04:40:41

问题


It is possible to set default value on DATE (NOT DATETIME) column in MySQL 5.7 to current date?
I try this (generated by Workbench):

ALTER TABLE `db`.`table` CHANGE COLUMN `column` `column` DATE NOT NULL DEFAULT CURDATE() ;

but not works for me. (no data in table)


回答1:


No, you cannot. The documentation is pretty clear on this:

This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. The exception is that you can specify CURRENT_TIMESTAMP as the default for TIMESTAMP and DATETIME columns. See Section 12.3.5, “Automatic Initialization and Updating for TIMESTAMP and DATETIME”.

You can do one of the following:

  • Set up a column with a default value for the DATETIME. Create view that extracts the date as a separate column.
  • Create an insert trigger to set the date column.



回答2:


There is a way you can do this if you have another column that has a for example a datetime field with a default of NOW(). See this post:



来源:https://stackoverflow.com/questions/39808684/mysql-date-field-with-default-curdate-not-datetime

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