UPDATE on INSERT duplicate primary key in Oracle?

后端 未结 3 1012
攒了一身酷
攒了一身酷 2020-12-22 02:07

I have a simple INSERT query where I need to use UPDATE instead when the primary key is a duplicate. In MySQL this seems easier, in Oracle it seems I need to use MERGE.

3条回答
  •  旧巷少年郎
    2020-12-22 02:58

    MERGE is the 'do INSERT or UPDATE as appropriate' statement in Standard SQL, and probably therefore in Oracle SQL too.

    Yes, you need a 'table' to merge from, but you can almost certainly create that table on the fly:

     MERGE INTO Movie_Ratings M
           USING (SELECT 1 AS mid, 3 AS aid, 8 AS rating FROM dual) N
              ON (M.mid = N.mid AND M.aid = N.aid)
           WHEN     MATCHED THEN UPDATE SET M.rating = N.rating
           WHEN NOT MATCHED THEN INSERT(  mid,   aid,   rating)
                                 VALUES(N.mid, N.aid, N.rating);
    

    (Syntax not verified.)

提交回复
热议问题