UPDATE记录(如果存在);否则在Oracle中插入

时间:2011-01-21 23:38:37

标签: sql oracle oracle10g insert-update ora-00904

是否有任何Oracle函数表明存在记录或任何其他有用的技术来实现这一目标?

编辑:使用我做的MERGE语句:

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);

我收到错误消息,指出col3是无效的标识符。没有拼写错误,它是现有的column.p_val1,p_val2,p_val3和p_val4是传递给存储过程的字符串参数。我认为问题可能在于这些参数,也许它们应该放在WHERE语句中? 有什么想法吗?

2 个答案:

答案 0 :(得分:4)

您正在Oracle中寻找merge

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 );

答案 1 :(得分:3)