How do you set a default value for a MySQL Datetime column?
In SQL Server, it's getdate(). What is the equivalant for MySQL?
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.
1. Create table
Create table test
(
id integer,
CreatedOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Or get around the problem using a trigger,Create trigger to set value everytime new row is inserted.
CREATE TRIGGER TRIG_test_CreatedOn
BEFORE INSERT
ON test
FOR EACH ROW
SET NEW.CreatedOn = NOW();
2. Existing Datetime column?
CREATE TRIGGER TRIG_test2_CreatedOn
BEFORE INSERT
ON test2
FOR EACH ROW
SET NEW.CreatedOn = NOW();
Or
alter table test2 CHANGE COLUMN CreatedOn CreatedOn TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
In SQL Server, it's getdate(). What is the equivalant for MySQL?
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.
1. Create table
Create table test
(
id integer,
CreatedOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Or get around the problem using a trigger,Create trigger to set value everytime new row is inserted.
CREATE TRIGGER TRIG_test_CreatedOn
BEFORE INSERT
ON test
FOR EACH ROW
SET NEW.CreatedOn = NOW();
2. Existing Datetime column?
CREATE TRIGGER TRIG_test2_CreatedOn
BEFORE INSERT
ON test2
FOR EACH ROW
SET NEW.CreatedOn = NOW();
Or
alter table test2 CHANGE COLUMN CreatedOn CreatedOn TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;