代码之家  ›  专栏  ›  技术社区  ›  Bigeyes

更新前检查记录是否存在

  •  0
  • Bigeyes  · 技术社区  · 7 年前

    我想更新一个表,但我想检查记录是否存在。如果没有,则抛出异常。在C#应用程序中,我传递参数并通过以下命令执行命令。

    procedure usp_update_example
    (
       p_id            in mydb.member.idn_member%type,
       p_idn_person    in mydb.member.idn_person%type,
       p_ind_rep       in mydb.member.ind_rep%type
    ) 
    as
        v_exist   pls_integer := 0;
        v_step    varchar2(250);
        v_exception_not_exist exception;
    begin
        v_step := 'Check for record '  || p_id;
        select count(1)
          into v_exist
          from mydb.member
          where idn_member = p_id;
    
          if v_exist = 0 then
             raise v_exception_not_exist;
          end if;
    
          if (v_exist > 0) then
          v_step := 'Update table :' || p_id;
          update mydb.member
          set
             idn_person   =  p_idn_person,
             ind_rep      =  p_ind_rep
          where idn_member = p_id;
          end if;
       exception
       when v_exception_not_exist then
         Raise_application_error(-20001, 'Not exist');
    end usp_update_example;
    

    然而,即使我的条件是正确的,我也有表中存在的记录。我总是很紧张 Not exist 例外如果我不使用 if v_exist = 0 WHEN NO_DATA_FOUND THEN . 那么一切都好了。

    我不确定哪里错了。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Maxim Borunov    7 年前

    您的代码似乎很好。看起来此问题与某些未提交的数据有关-您在插入记录的会话中看到该记录,但在C#会话中看不到该记录,因为该记录尚未提交。因此,C#会话生成异常。

    我建议重新编写过程代码,使其更加紧凑。

    ...
    begin
      update mydb.member
      set    idn_person   =  p_idn_person,
             ind_rep      =  p_ind_rep
      where idn_member = p_id;
    
      if SQL%ROWCOUNT = 0 then
        raise_application_error(-20001,'Not exist');
      end if;
    end;