Search code examples
sqloracle-databaseoracle10ginsert-updateora-00904

UPDATE record if present; else INSERT in Oracle


Is there any Oracle function that indicate the existence of a record, or any other useful technique to achieve this?

EDIT: using the MERGE statement I did:

MERGE
 INTO  lims_min.mytab src
 USING lims_min.mytab tgt
    ON (    src.col1 = tgt.col1
        AND tgt.col1 = p_val1
        AND src.col2 = tgt.col2
        AND tgt.col2 = p_val2
       )

 WHEN MATCHED
 THEN
 UPDATE
  SET tgt.col3=p_val3,
      tgt.col4=p_val4

 WHEN NOT MATCHED
 THEN
 INSERT  (col1, col2, col3, col4)
 VALUES  (val1, val2, val2, val4);

I get the error saying that col3 is invalid identifier. No typos, and it is existing column.p_val1, p_val2, p_val3 and p_val4 are string parameters that are passed to the stored procedure. i am thinking that the issue may lie in these params, perhaps they should be placed inside a WHERE statement? Any ideas?


Solution

  • You are looking for merge in Oracle.

    MERGE
           INTO  target_table tgt
          USING source_table src
             ON  ( src.object_id = tgt.object_id ) //The key to check if the record exists
           WHEN MATCHED // if exists
           THEN
         UPDATE
            SET   tgt.object_name = src.object_name //update it
            ,     tgt.object_type = src.object_type
           WHEN NOT MATCHED                         // if not exists
           THEN
         INSERT ( tgt.object_id                    //then insert
                , tgt.object_name
                , tgt.object_type )
         VALUES ( src.object_id
                , src.object_name
                , src.object_type );