views:

1997

answers:

2

I'm using the latest version of MySql and I tried altering a table to use curtime() or now() or current_timestamp as the default value for a datetime column (created_at, updated_at). For all three, the alter failed, saying these are invalid default values. Any ideas what's an appropriate default value to generate the current time in a datetime field?

ALTER TABLE `music_library_development`.`albums` 
MODIFY COLUMN `created_at` DATETIME NOT NULL DEFAULT current_timestamp,
MODIFY COLUMN `updated_at` DATETIME NOT NULL DEFAULT current_timestamp;

ALTER TABLE `music_library_development`.`albums` 
MODIFY COLUMN `created_at` DATETIME NOT NULL DEFAULT now(),
MODIFY COLUMN `updated_at` DATETIME NOT NULL DEFAULT now();

ALTER TABLE `music_library_development`.`albums` 
MODIFY COLUMN `created_at` DATETIME NOT NULL DEFAULT curtime(),
MODIFY COLUMN `updated_at` DATETIME NOT NULL DEFAULT curtime();
+1  A: 

Try using the TIMESTAMP column type:

MODIFY COLUMN `updated_at` TIMESTAMP NOT NULL DEFAULT current_timestamp;
Chris Bartow
I just tried that. It says there can only be one timestamp column with a default value set.
pez_dispenser
Yes, you can't have multiple columns that auto update. This was addressed on another question, but I can't find it.
Chris Bartow
A: 

alter table music_library_development change created_at created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

alter table music_library_development change updated_at updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP