2017-07-11 12 views
1

嘗試基於reference_no有效地檢查記錄是否存在,如果它確實返回了它的ID,如果不插入它並返回一個新的ID。編寫Oracle函數檢查記錄是否存在,如果不將它合併到同一個表中

也許合併是不是要走的路?

找不到語法!

create or replace FUNCTION get_note_history_id( 
    p_owner_id VARCHAR2, --to insert to the note history table 
    p_open_date DATE, --to insert to the note history table 
    p_note_log CLOB, --to insert to the note history table 
    p_collection_id VARCHAR2, --not to break the previous code 
    p_reference_no NUMBER --correlates to the notice (date) sent) 
) 


return VARCHAR2 is 
v_note_history_id NUMBER 

MERGE INTO NOTE_HISTORY n 
USING(

    select NOTE_HISTORY_ID 
    from NOTE_HISTORY 
    where p_reference_no = n.notice_reference_no 
) h 

WHEN MATCHED THEN 
    v_note_history_id := h.NOTE_HISTORY_ID; 

WHEN NOT MATCHED THEN 

    INSERT INTO NOTE_HISTORY (create_user_id,create_date,note,collection_id,notice_reference_no) 
    VALUES (p_owner_id,p_open_date,p_note_log,p_collection_id,p_reference_no) returning NOTE_HISTORY_ID into v_note_history_id; 

RETURN v_note_history_id; 


END get_note_history_id;     
+0

合併是一個結合了更新和插入的SQL DML語句。不是可以有條件地執行任意PL/SQL語句的PL/SQL控制語句流。返回子句適用於插入,但不適用於合併的插入臂。 –

回答

1

您的方法有幾個問題。 MERGE純粹是一個SQL構造,所以我們不能在其中包含PL/SQL代碼。另外,MERGE不支持RETURNING子句(這很煩人)。

所有這些意味着您需要實施一個老式的UPSERT。您可以嘗試更新並切換到no_data_found上的INSERT,或者使用INSERT並切換到dup_val_on_index上的更新。這個決定應該基於普遍的路徑:如果你期望主要匹配首先進行更新,主要缺失將用於INSERT。如果您在notice_reference_no(tsk,tsk)上沒有唯一約束,則無論如何您都需要使用UPDATE。

雖然你不是實際更新的WHEN MATCHED手臂任何一個簡單的查詢就足夠了:

create or replace FUNCTION get_note_history_id( 
    p_owner_id VARCHAR2, --to insert to the note history table 
    p_open_date DATE, --to insert to the note history table 
    p_note_log CLOB, --to insert to the note history table 
    p_collection_id VARCHAR2, --not to break the previous code 
    p_reference_no NUMBER --correlates to the notice (date) sent) 
) 
is 
    v_note_history_id number; 
begin 
    begin 
    select n.note_history_id 
    into v_note_history_id 
    from NOTE_HISTORY n 
    where n.notice_reference_no = p_reference_no ; 
    exception 
    WHEN no_data_found THEN 
     INSERT INTO NOTE_HISTORY (create_user_id,create_date,note,collection_id,notice_reference_no) 
     VALUES (p_owner_id,p_open_date,p_note_log,p_collection_id,p_reference_no) 
     returning NOTE_HISTORY_ID into v_note_history_id; 
    end; 
    return v_note_history_id; 
end; 
/

作爲一項規則我不喜歡使用異常塊的處理究竟是正常的業務處理,但其他方法更不雅觀。

+0

非常感謝這! – JohnnyO

相關問題