rahimi
rahimi

Reputation: 13

Update else INSERT in mysql

I tested this code:

UPDATE books SET price='20000' WHERE user_id='2'
IF ROW_COUNT()=0
INSERT INTO store_books(name,user_id) VALUES ('test1','2')

I encountered the following error.

error : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'IF ROW_COUNT()=0 INSERT INTO store_books(name,user_id) VALUES ('test1','2')' at line 2

Is there any solution to solve this problem?

I don't want to use INSERT INTO ... ON DUPLICATE KEY UPDATE (because i have multi keys in my main table).

Above example is trial for finding new way.

Pattern that i want: Update(if exists) ELSE Insert.

Upvotes: 1

Views: 82

Answers (1)

O. Jones
O. Jones

Reputation: 108696

Two things:

  1. INSERT ... ON DUPLICATE KEY UPDATE ... is by far the best way to do what you want to do. If you don't do this, you'll have to use a database transaction to make sure you maintain integrity for the operation you want.
  2. MySQL (unlike, say, MS SQL server) doesn't allow conditional execution of queries except in stored procedures. Read this. If conditional in SQL Script for Mysql

Upvotes: 1

Related Questions