簡體   English   中英

oracle sql中存儲過程中的錯誤處理失敗

[英]Error handling in a stored procedure in oracle sql failed

我正在使用存儲過程在 oracle SQL 中插入一個表,如果我創建的健康記錄的數量已經存在,我想引發一個錯誤,不允許在表中插入值。 這是代碼:

BEGIN
SELECT MAHDAR_NUM INTO L_MAHDAR_NUM FROM MEDICALPST.mahdar WHERE MAHDAR_NUM=i.MAHDAR_NUM;
exception when others then
P_MSG:=NULL;
END;

IF L_MAHDAR_NUM IS NOT NULL
THEN
P_MSG:=006;
ROLLBACK;
END IF;

IF P_MSG IS NULL
THEN
INSERT INTO medicalpst.mahdar 
VALUES (L_MAHDAR_SEQ,
        L_DECISION_SEQ,
        NULL,
        NULL,
        NULL,
       ...

但是,當我插入一個已經存在的MAHDAR_NUM時,它不會引發錯誤,並且無論如何都會在表中插入值。 我將不勝感激任何幫助 :)

在我看來,你做錯了。

MADHAR_NUM列上應該有一個主(或唯一)鍵,以防止輸入重復項。 它有什么好處? 數據庫會處理重復項,您無需執行任何操作(除非您願意)。 在這種情況下,代碼將非常簡單

begin
  insert into madhar (col1, col2, col3, ...)
    values (l_madhar_seq, l_decision_seq, null, ...);
exception
  when dup_val_on_index then 
    null;
end;    

(我不知道l_madhar_seq, l_decision_seq來自哪里,但是 - 根據它們的名稱,它們看起來像本地聲明的變量。你應該知道)。


如果出於某種原因,您不想讓數據庫為您處理重復項,請考慮如下操作:

declare
  l_madhar_num madhar.madhar_num%type;
begin
  for i in (select madhar_num, ... from some_table where some_conditions) loop
    begin
      -- if this SELECT returns a value, nothing will happen as no commands
      -- follow the SELECT
      select madhar_num
        into l_madhar_num
        from madhar
        where madhar_num = i.madhar_num;
    exception
      -- but, if that SELECT returns nothing, NO_DATA_FOUND will be raised
      -- which means that you should insert a new row into a table.
      when no_data_found then
        insert into madhar (col1, col2, col3, ...)
        values (l_madhar_seq, l_decision_seq, null, ...);
    end;
  end loop;
end;    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM