mysql set field default value to other column

99封情书 提交于 2019-11-28 22:51:01
eggyal

As documented under Data Type Default Values:

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. See Section 11.3.5, “Automatic Initialization and Updating for TIMESTAMP.

Instead, you can define an insertion trigger:

CREATE TRIGGER foo BEFORE INSERT ON TSM_TRANSACTION_TBL FOR EACH ROW
  IF NEW.REMAINING IS NULL THEN
    SET NEW.REMAINING := NEW.MAX_VALUE - NEW.BOOKED_UNITS;
  END IF;;
Darkside

The 'NEW' is unacceptable for AFTER insert triggers. You should do the 'field update' by a BEFORE insert trigger. So,

CREATE TRIGGER foo BEFORE INSERT ON TSM_TRANSACTION_TBL FOR EACH ROW
    IF NEW.REMAINING IS NULL THEN
        SET NEW.REMAINING := NEW.MAX_VALUE - NEW.BOOKED_UNITS;
    END IF;;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!