Reputation: 13
I need trigger to add current date (only date not time) on every insert in my table.
CREATE TRIGGER set_created_date
BEFORE INSERT ON people
FOR EACH ROW BEGIN
SET NEW.created_date = date();
END;
this is my code. what am i doing in wrong? thank you
Upvotes: 1
Views: 67
Reputation: 43574
You can use the following solution:
USE db_name; -- or select the database with script / tool
DELIMITER |
CREATE TRIGGER set_created_date BEFORE INSERT ON people
FOR EACH ROW
BEGIN
SET NEW.created_date = CURDATE();
END;
|
DELIMITER ;
notes / explanation:
DELIMITER
so MySQL can handle the ;
correctly.DATE
function extracts the date part of a datetime value.CURDATE
or DATE(NOW())
.Difference between this TRIGGER
and a column DEFAULT
:
In case you are using a DEFAULT
value on the column created_date
the default value is only set to the column if no value is provided for this column on INSERT
. So if someone run a INSERT
command like the following:
INSERT INTO people (name, created_date) VALUES ('John Doe', '2017-02-03');
the default value (the current date) is not set to the column. Instead the available value will be set to the column (2017-02-03
).
The TRIGGER
set the current date on every INSERT
. If someone execute the above INSERT
command still the current date will be set to the created_date
column (not the value provided on the INSERT
command).
Upvotes: 3
Reputation: 23361
Why a trigger? Why not set your create_date
field default now()
alter table people modify column create_date datetime default now();
Here it is showing how it works: http://sqlfiddle.com/#!9/50a441/1
Upvotes: 1