2

I've created a table in mySQL like this:

CREATE TABLE IF NOT EXISTS `LibraryManager`.`Card` (
  `card_id` INT NOT NULL AUTO_INCREMENT,
  `card_registerDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `card_expiredDate` TIMESTAMP,
  PRIMARY KEY (`card_id`))
ENGINE = InnoDB;

Now I want to set the default value of card_expiredDate to card_registerDate + 30 or CURRENT_TIMESTAMP + 30 (30 day from register date). Is there any way to do that? Thank you very much for reading this.

vunguyenhung
  • 79
  • 1
  • 5

2 Answers2

1

Create an AFTER INSERT trigger, it will do the job for you:

DELIMITER $$
CREATE TRIGGER set_expiration_date
AFTER INSERT ON `LibraryManager` FOR EACH ROW
BEGIN

    UPDATE LibraryManager 
    SET card_expiredDate = DATE_ADD(NEW.card_registerDate, INTERVAL 30 DAY)
    WHERE card_id = NEW.card_id;

END;
$$
DELIMITER ;

PS: I haven't tested it, if you get any error do let me know.

Shaharyar
  • 12,254
  • 4
  • 46
  • 66
  • 1
    It's better to use `BEFORE INSERT` trigger and calculate value before insert instead of perform second `UPDATE` query. – Andrew Apr 23 '16 at 08:19
1

Setting the default value for expiry column using create statement is not possible as such, instead use trigger. For that you will have to slightly modify you create statement. Just change the datatype of expiry column, your new query:

CREATE TABLE IF NOT EXISTS `LibraryManager`.`Card` (
`card_id` INT NOT NULL AUTO_INCREMENT,
`card_registerDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`card_expiredDate` DATETIME,
PRIMARY KEY (`card_id`))
ENGINE = InnoDB;

and then fire the following trigger

CREATE TRIGGER before_insert_library_card
BEFORE INSERT ON `LibraryManager`.`Card` 
FOR EACH ROW
SET new.card_expiredDate = adddate(CURRENT_TIMESTAMP,30);

hope this helps.

P.S: Triggers slow down your insert operations(or whatever operation they are applied before/after). I suggest you set these values programmatically using php/python or whatever the backend you are using.

Related:

Can I use a function for a default value in MySql?

Community
  • 1
  • 1
Shekhar Joshi
  • 958
  • 1
  • 13
  • 26