MySQL - Set default value for field as a string concatenation function
MySQL does not support computed columns or expressions in the DEFAULT
option of a column definition.
You can do this in a trigger (MySQL 5.0 or greater required):
CREATE TRIGGER format_stage_name
BEFORE INSERT ON actors
FOR EACH ROW
BEGIN
SET NEW.stage_name = CONCAT(NEW.forename, ' ', NEW.surname);
END
You may also want to create a similar trigger BEFORE UPDATE
.
Watch out for NULL
in forename and surname, because concat of a NULL
with any other string produces a NULL
. Use COALESCE()
on each column or on the concatenated string as appropriate.
edit: The following example sets stage_name
only if it's NULL
. Otherwise you can specify the stage_name
in your INSERT
statement, and it'll be preserved.
CREATE TRIGGER format_stage_name
BEFORE INSERT ON actors
FOR EACH ROW
BEGIN
IF (NEW.stage_name IS NULL) THEN
SET NEW.stage_name = CONCAT(NEW.forename, ' ', NEW.surname);
END IF;
END
According to 10.1.4. Data Type Default Values no, you can't do that. You can only use a constant or CURRENT_TIMESTAMP
.
OTOH if you're pretty up-to-date, you could probably use a trigger to accomplish the same thing.