How to set default value for a field to other column in MySQL?
I have done it in Oracle with virtual field, but I do not know how to do it in MySQL.
This is my table:
CREATE TABLE TSM_TRANSACTION_TBL ( TRANS_ID INT primary key auto_increment, LOCATION_ID INT, TRANS_DATE DATE, RESOURCE_ID INT, TS_ID INT, MAX_VALUE INT, BOOKED_UNITS INT default 0, REMAINING INT default MAX_VALUE - BOOKED_UNITS, BOOKED INT not null, USER_ID INT, TRANS_TIME TIMESTAMP );
A column's default value is part of its definition, but can be modified separately from other aspects of the definition. To change a default value, use ALTER col_name SET DEFAULT : ALTER TABLE mytbl ALTER j SET DEFAULT 1000; Default values must be constants.
You can use the ALTER TABLE statement to add, change, or remove the default value for a column.
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 asNOW()
orCURRENT_DATE
. The exception is that you can specifyCURRENT_TIMESTAMP
as the default for aTIMESTAMP
column. See Section 11.3.5, “Automatic Initialization and Updating forTIMESTAMP
”.
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;;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With