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

后端 未结 26 2215
野的像风
野的像风 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

    You can use triggers to do this type of stuff.

    CREATE TABLE `MyTable` (
    `MyTable_ID`  int UNSIGNED NOT NULL AUTO_INCREMENT ,
    `MyData`  varchar(10) NOT NULL ,
    `CreationDate`  datetime NULL ,
    `UpdateDate`  datetime NULL ,
    PRIMARY KEY (`MyTable_ID`)
    )
    ;
    
    CREATE TRIGGER `MyTable_INSERT` BEFORE INSERT ON `MyTable`
    FOR EACH ROW BEGIN
            -- Set the creation date
        SET new.CreationDate = now();
    
            -- Set the udpate date
        Set new.UpdateDate = now();
    END;
    
    CREATE TRIGGER `MyTable_UPDATE` BEFORE UPDATE ON `MyTable`
    FOR EACH ROW BEGIN
            -- Set the udpate date
        Set new.UpdateDate = now();
    END;
    

提交回复
热议问题