【问题标题】:Update and insert in oracle PL/SQL along with if else condition在 oracle PL/SQL 中更新和插入以及 if else 条件
【发布时间】:2015-09-06 21:13:50
【问题描述】:

请通过以下代码 sn-p 查找:

BEGIN
  IF (in_config1 IS NOT NULL OR in_config1 !='') THEN
      UPDATE question_table
      SET comment = in_config1 
      WHERE id= id
      AND questionid = 1;
  ELSE
      INSERT INTO question_table(
      tid
      ,questionid 
      ,comments) 
      VALUES( id
      , 1
      , in_config1);
 END IF;
 END;

我的要求是根据某些条件更新 question_table。如果更新失败,如果记录不存在,那么我需要在 else 块中添加插入语句。 在上面的代码更新工作。但是插入语句没有被执行。请问有什么问题吗?

【问题讨论】:

  • 您是否遇到任何错误?您尝试过哪些示例数据?
  • 不,我没有收到任何错误。基本上我想将其修改为 upsert 语句。如果行匹配则更新行否则插入行

标签: plsql oracle11g plsqldeveloper


【解决方案1】:

如果我理解你,你需要 upsert 语句,如果记录匹配某个值,则在其中更新,如果不匹配,则插入。在这种情况下,最好的选择是MERGE 子句。它高效、灵活且易读。以下是一个通用脚本,可能需要根据您从中获取值的位置和表结构进行细微更改。

MERGE INTO question_table a   
USING (SELECT id, your_key, in_config1 FROM DUAL) b   
ON (a.id = b.id)   
WHEN MATCHED THEN   
UPDATE question_table   
SET comment = in_config1   
WHEN NOT MATCHED THEN   
INSERT INTO question_table(   
      tid  
     ,questionid    
     ,comments)   
     VALUES( id  
     , 1  
     , in_config1);   

【讨论】:

    【解决方案2】:

    你可以这样做使用 sql%notfound

      BEGIN
        IF (in_config1 IS NOT NULL OR in_config1 != '') THEN
          UPDATE question_table
             SET comment = in_config1
           WHERE id = id
             AND questionid = 1;
          if sql%notfound then
            INSERT INTO question_table (tid, questionid, comments) VALUES (id, 1, in_config1);
          end if;
        END IF;
      exception
        when others then
          dbms_output.put_line(sqlerrm);
      END;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 2016-01-03
      • 2021-11-14
      相关资源
      最近更新 更多