Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle: ON DUPLICATE KEY UPDATE [duplicate]

Tags:

sql

oracle

upsert

I'm trying to implement a solution I found over here from Michiel de Mare to update multiple records with one (preferably-simple-in-a-syntax-sense) query. The example code that I am trying to learn from looks like this:

INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12) ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);

I'm using Oracle (and am not yet well versed in SQL queries).

Based on some dynamic content, I have concatenated my query similar to the above. It can vary in length depending on how many records I am updating, but this is an example of a query that I generated:

INSERT INTO my_table (question_id,ug) VALUES (30,0),(31,1) ON DUPLICATE KEY UPDATE ug=VALUES(ug) 

The above query is getting this error:

Native message: ORA-00933: SQL command not properly ended

I am dealing with a content management system that has a function call that runs the queries; within this framework. I don't think it is pertinent, but I have never needed to put a ';' on the end of queries, however, I tried it with and without the semicolon.

like image 642
John Avatar asked Dec 11 '22 14:12

John


1 Answers

Oracle doesn't have on duplicate key update Use MERGE instead:

MERGE INTO my_table trg  
USING (SELECT 30 as question_id,0 as ug FROM DUAL
UNION ALL 
SELECT 31,1 FROM DUAL) src ON (src.question_id = trg.question_id)
WHEN NOT MATCHED THEN INSERT(question_id, ug) VALUES
(src.question_id, src.ug)
WHEN MATCHED THEN UPDATE
SET trg.ug = src.ug
like image 167
a1ex07 Avatar answered Dec 22 '22 01:12

a1ex07