[英]How do I set “MONTHNAME()” function as column default in MySQL?
Actually I need current month name as lowercase string as default value in one of the table column; 实际上, 我需要在表列之一中将当前月份名称作为小写字符串作为默认值。 DB table may look like Like: 数据库表可能看起来像:
name : john
joined : january
When I try to use mysql function LOWER( MONTHNAME( NOW() ) )
as defailt value this gives me error. 当我尝试使用mysql函数LOWER( MONTHNAME( NOW() ) )
作为默认值时,这给了我错误。 Btw I'm not interested in creating triggers. 顺便说一句,我对创建触发器不感兴趣。
any magic queries to do that? 任何魔术查询可以做到这一点?
From the MySQL documentation : 从MySQL 文档 :
With one exception, enclose expression default values within parentheses to distinguish them from literal constant default values. 除一个例外,将表达式默认值括在括号内,以将其与文字常量默认值区分开。
So, the following should work: 因此,以下应工作:
CREATE TABLE yourTable (
month_name VARCHAR(12) DEFAULT (LOWER(MONTHNAME(NOW())))
...
)
As @Madhur has pointed out, using an expression as a default will only work from MySQL 8 onwards. 正如@Madhur指出的那样,使用表达式作为默认值仅适用于MySQL 8及更高版本。
If you use MySQL 8.0 or later, then the answers provided by @TimBiegeleisen and @fa06 should solve the problem. 如果使用MySQL 8.0或更高版本,则@TimBiegeleisen和@ fa06提供的答案应该可以解决问题。 In otherwise 换句话说
... the default value specified in a DEFAULT clause must be a literal constant; ... DEFAULT子句中指定的默认值必须是文字常量; it cannot be a function or an expression. 它不能是函数或表达式。
See details in documentation . 请参阅文档中的详细信息。
So, for previous versions you need to find another way. 因此,对于以前的版本,您需要找到另一种方法。 For example, you could define a trigger that sets default value for the column if the value is not specified: 例如,如果未指定值,则可以定义一个触发器 ,该触发器为列设置默认值:
CREATE TABLE MyTable (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
joined VARCHAR(12)
);
CREATE TRIGGER defaultMonth
BEFORE INSERT ON MyTable
FOR EACH ROW
SET NEW.joined = IFNULL(NEW.joined, LOWER(MONTHNAME(NOW())));
See also live example for the proposed solution. 有关建议的解决方案,另请参见实时示例 。
You can try below 您可以在下面尝试
CREATE TABLE orderdata (
order_date DATE
, order_month VARCHAR(50) AS (lower(MONTHNAME(order_date)))
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.