MySQL default date() + 14 days, for a column?

跟風遠走 提交于 2019-11-29 15:01:40
Naveen Kumar

Create a table and set up a trigger for that table.

CREATE TABLE product(
    product_id INT PRIMARY KEY,
    product VARCHAR(40),
    entryDate DATETIME,
    expDate DATETIME
);

CREATE TRIGGER test_trigger BEFORE INSERT ON `product` 
FOR EACH ROW SET
    NEW.entryDate = IFNULL(NEW.entryDate, NOW()),
    NEW.expDate = TIMESTAMPADD(DAY, 14, NEW.entryDate);

On each insert into the table, the trigger sets the entryDate to the current time and expDate to 14 days time.

You can use this by using DateTime methods in MySQL:

DATE_ADD(date_starts,INTERVAL 14 DAY)

for example:

UPDATE events SET date_starts = DATE_ADD(date_starts,INTERVAL 14 DAY) WHERE event_id = 3;

For more details go here.

you can try this this function

DATE_ADD(now(), INTERVAL 14 DAY);

According to this source you can't use expressions as a default specifier.

So not sure if it has changed since the bug was posted.

I'm not sure however why I assumed that the OP wants to define it as a default value.

date = DATE_ADD(NOW(), INTERVAL 14 DAY)

or as said, alter your table structure for that field (attribute for that field=) to "on Update CURRENT_TIMESTAMP"

I believe MySQL won't allow you to use expressions in the default value. You might want to write a trigger.

MySQL does provide a TIMESTAMP datatype which can be set to CURRENT_TIMESTAMP when a row is created or updated. You might find this feature somewhat useful:

CREATE TABLE table1 (
    `Column1` VARCHAR(50) NULL,
    `Created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)

Once you're sure that MySQL is filling that column as expected, you can write queries like this:

SELECT `Created`, `Created` + INTERVAL 14 DAY AS `expiry_date`
FROM table1

The easiest way to solve that is just insert the value you want - without trigger or later update, eg.

 INSERT INTO <your_table> (name, expiry_date) VALUES ('foo', DATE_ADD(CURRENT_TIMESTAMP,INTERVAL 7 DAY))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!