Search code examples
mysqlreplaceifnulloptional-values

mysql REPLACE INTO and optional values IFNULL


I'm trying to do something like this inside of a stored procedure:

REPLACE INTO mytable
SET myid = `IDvalue`, mytitle = `sMyTitle`, myoptionalvalue = IFNULL(`sMyOptValue`, myoptionalvalue);

But not seems to work, any idea how to do this?

Thanks!


Solution

  • The REPLACE INTO syntax works exactly like INSERT INTO except that any old rows with the same primary or unique key is automaticly deleted before the new row is inserted.

    This means that instead of a WHERE clause, you should add the primary key to the values beeing replaced to limit your update.

    REPLACE INTO myTable (
     myPrimaryKey,
     myColumn1,
     myColumn2
      ) VALUES (
     100,
     'value1',
     'value2'
     );
    

    ...will provide the same result as...

    UPDATE myTable
    SET myColumn1 = 'value1', myColumn2 = 'value2'
    WHERE myPrimaryKey = 100;