Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
MySQL: Adding Calculated Column with IF ELSEIF

I'm struggling with an Alter Table scenario. I have a table "example" with columns 1 to 3 existing. I want to add a column "destination" which than should contain either a value from column2 or from column3 depending on column1. I tried the following code but it throws errors at the first line of the IF statement. Error is with the column1 reference, it is expecting an opening parenthesis but when I put the IF clause' condition in parantheses, it is rejecting the THEN function. MySQL 8.0 See code below. Who can help? Many thanks, Thomas


ADD COLUMN
(
Destination VARCHAR(15) 
GENERATED ALWAYS AS 
    (
    IF column1 = "north" THEN
        SET destination = column2
    ELSEIF column1 = "south" THEN   
        SET destination = column3
    ELSE
        SET destination = ""
    END IF
    )
STORED
)
;
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use the following syntax( containing CASE..WHEN..ELSE Statement instead of IF..THEN..ELSE ) of Generated Column which's released in DB version 5.7+ :

ALTER TABLE t1 ADD COLUMN
(
Destination VARCHAR(15) 
GENERATED ALWAYS AS 
    (
    CASE WHEN column1 = "north" THEN
           column2
         WHEN column1 = "south" THEN   
           column3    
    END 
    )
STORED
)

without assignment to the derived column itself and without set clause.

Demo

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda