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

后端 未结 26 2186
野的像风
野的像风 2020-11-22 01:55

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

In SQL Server it\'s getdate(). What is the equivalant for MySQL? I\'m using MySQL 5.x if tha

26条回答
  •  既然无缘
    2020-11-22 02:35

    I was able to solve this using this alter statement on my table that had two datetime fields.

    ALTER TABLE `test_table`
      CHANGE COLUMN `created_dt` `created_dt` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
      CHANGE COLUMN `updated_dt` `updated_dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
    

    This works as you would expect the now() function to work. Inserting nulls or ignoring the created_dt and updated_dt fields results in a perfect timestamp value in both fields. Any update to the row changes the updated_dt. If you insert records via the MySQL query browser you needed one more step, a trigger to handle the created_dt with a new timestamp.

    CREATE TRIGGER trig_test_table_insert BEFORE INSERT ON `test_table`
        FOR EACH ROW SET NEW.created_dt = NOW();
    

    The trigger can be whatever you want I just like the naming convention [trig]_[my_table_name]_[insert]

提交回复
热议问题