0

I'm trying a IF statement inside of SQL code but I'm getting a sintax error, SQL always mess up my thinking.

What I'm trying is set a COUNT inside of a VAR and them use this VAR to define a UPDATE or INSERT command, something like:

SELECT COUNT(id) INTO @id FROM table1;
IF @id > 0 THEN 
  UPDATE
ELSE
  INSERT;

Help is always wellcome.

  • You have to write the whole update / insert command. `insert` is not a complete command. So do `IF @id > 0 THEN UPDATE table1 set a = b where id = 5 else insert into table1 ... ;` But I guess what you actually want to do is to check if an id already exists and then update this id or insert this id. In that case, have a look [here](http://stackoverflow.com/questions/6030071/mysql-table-insert-if-not-exist-otherwise-update) – Solarflare May 29 '16 at 20:51

1 Answers1

0

Convert the entire code to use of INSERT ... ON DUPLICATE KEY UPDATE .... That single SQL statement will 'insert' new records or update existing records.

Rick James
  • 135,179
  • 13
  • 127
  • 222