Skip to content Skip to sidebar Skip to footer

Setting Columns Variably In Mysql

What would be the syntax for doing the following: INSERT INTO table SET IF *expression* column1 = 'value1' ELSE column2 = 'value2'

Solution 1:

You would use insert . . . select with a case statement:

INSERTINTOtable(column1, column2)
    select (casewhen*expression*then'value1'end) as column1,
           (casewhennot*expression*then'value2'end) as column2;

However, I suspect that you might really want an update and not an insert:

updatetableset column1 = (casewhen*expression*then'value1'else column1 end),
        column2 = (casewhennot*expression*then'value2'else column2 end);

Post a Comment for "Setting Columns Variably In Mysql"