mysql 默认当前年份,MySQL:将当前年份添加为字段“ year”的默认值

I have the following table in MySQL (version 5):

id int(10) UNSIGNED No auto_increment

year varchar(4) latin1_swedish_ci No

title varchar(250) latin1_swedish_ci Yes NULL

body text latin1_swedish_ci Yes NULL

And I want the db to auto add the current year on insert, I've tried the following SQL statement:

ALTER TABLE `tips` CHANGE `year` `year` VARCHAR(4) NOT NULL DEFAULT year(now())

But it gives the following error:

1067 - Invalid default value for 'year'

What can I do to get this functionality? Thanks in advance!

解决方案The DEFAULT value clause in a data

type specification indicates a default

value for a column. With one

exception, the default value must be a

constant; it cannot be a function or

an expression. 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 a TIMESTAMP column.

You can, however, write a trigger that sets the value. I wish I could help, but I'm not really familiar with writing stored procedures in MySQL.

I think this would work:

CREATE TRIGGER ins_year

BEFORE INSERT ON tips

FOR EACH ROW SET NEW.year = YEAR(NOW());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值