MySQL - Set default value for field as a string concatenation function

后端 未结 3 1954
面向向阳花
面向向阳花 2021-02-05 23:31

I have a table that looks a bit like this actors(forename, surname, stage_name);

I want to update stage_name to have a default value of

forename.\" \".su         


        
3条回答
  •  不知归路
    2021-02-06 00:03

    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
    

提交回复
热议问题