如何将MySQL DateTime(不是TIMESTAMP)的默认值设置为NOW()或Current_DateTIme? [重复]

时间:2022-10-22 18:17:38

Possible Duplicate:
How do you set a default value for a MySQL Datetime column?

可能重复:如何为MySQL Datetime列设置默认值?

I have a table with column CreatedDate of data type datetime and i want to be able to set its default value to current DateTime how do i do it?

我有一个数据类型为datetime的列CreatedDate的表,我希望能够将其默认值设置为当前DateTime我该怎么做?

I tried Now() and CurrentTimestamp but no luck so far!!!

我试过Now()和CurrentTimestamp但到目前为止没有运气!

2 个解决方案

#1


5  

You can only set a static default in the table definition.
So unless you want to call ALTER TABLE every minute....

您只能在表定义中设置静态默认值。所以,除非你想每分钟调用ALTER TABLE ....

Use a trigger:

使用触发器:

DELIMITER $$

CREATE TRIGGER bu_table1_each BEFORE UPDATE ON table1 FOR EACH ROW
BEGIN
  SET new.datefield = NOW();
END $$

DELIMITER ;

See: http://dev.mysql.com/doc/refman/5.5/en/triggers.html

#2


1  

I do not think you can do it with DateTime.

我不认为你可以用DateTime做到这一点。

See: How do you set a default value for a MySQL Datetime column?

请参阅:如何为MySQL Datetime列设置默认值?

#1


5  

You can only set a static default in the table definition.
So unless you want to call ALTER TABLE every minute....

您只能在表定义中设置静态默认值。所以,除非你想每分钟调用ALTER TABLE ....

Use a trigger:

使用触发器:

DELIMITER $$

CREATE TRIGGER bu_table1_each BEFORE UPDATE ON table1 FOR EACH ROW
BEGIN
  SET new.datefield = NOW();
END $$

DELIMITER ;

See: http://dev.mysql.com/doc/refman/5.5/en/triggers.html

#2


1  

I do not think you can do it with DateTime.

我不认为你可以用DateTime做到这一点。

See: How do you set a default value for a MySQL Datetime column?

请参阅:如何为MySQL Datetime列设置默认值?