2013-01-07 83 views
0

我已經發布此問題之前。但是現在我的項目經理回來並給了我一套新的說明。再一次,我現在有點失落,並試圖在一定程度上解決它。合併與選擇插入觸發器

我正在處理需要INSERT INTO和WHERE邏輯的觸發器。

我有三張桌子。

Absence_table:

----------------------------- 
| user_id | absence_reason | 
----------------------------- 
| 1234567 | 40   | 
| 1234567 | 50   | 
| 1213 | 40   | 
| 1314 | 20   | 
| 1111 | 20   | 
----------------------------- 

company_table:

----------------------------- 
| user_id | company_id  | 
----------------------------- 
| 1234567 | 10201   | 
| 1213  | 10200   | 
| 1314  | 10202   | 
| 1111  | 10200   | 
----------------------------- 

employment_table:

------------------------------------------- 
| user_id | emp_type | employee_id | 
------------------------------------------- 
| 1234567 | Int   | 1   | 
| 1213  | Int   | 2   | 
| 1314  | Int   | 3   | 
| 1111  | Ext   | 4   | 
------------------------------------------- 

最後我有表在哪裏數據應該會只有誰擁有EMP_TYPE = INT在employ_id = 10200

出來:

------------------------------------------- 
| employee_id | absence_reason | user_id | 
------------------------------------------- 
| 1   | 40   | 1234567 | 
| 1   | 50   | 1234567 | 
| 2   | 40   | 1213 | 
| 3   | 20   | 1314 | 
------------------------------------------- 

這裏是我的觸發器:

CREATE OR REPLACE TRIGGER "INOUT"."ABSENCE_TRIGGER" 
    AFTER INSERT ON arc_hrcs.absences_data 
    FOR EACH ROW 
DECLARE 
BEGIN 
    CASE 
     WHEN UPDATING THEN 
      MERGE INTO out o USING DUAL ON (out.user_id =:NEW.user_id) 
      WHEN MATCHED THEN UPDATE SET 
         out.employee_id = (SELECT employee_id FROM employment_table WHERE user_id = :NEW.user_id), 
         out.absence_reason = :NEW.absence_reason, 
         out.user_id = :NEW.user_id 
      WHEN NOT MATCHED THEN 


    insert into out (absence_reason, employee_id) 
select :NEW.absence_reason, e.employee_id 
    from employment_table e 
     inner join company_table c 
       on c.user_id = e.user_id 
where e.user_id = :NEW.user_id 
    and e.emp_type = 'INT' 
    and c.company_id = '10200'; 
    END CASE; 
END absence_trigger; 

我無法弄清楚如何改變WHEN NOT根據合併語法然後再配代碼之後的代碼。指南的位將幫助我:-)

在此先感謝。

+0

爲什麼你對用戶1234567兩種不同absence_reasons?在absence_table/out中爲同一用戶使用兩行真的有意義嗎? –

回答

2

我以前的答案是有點太快。

我會改寫合併爲:

MERGE INTO out o USING (select e.employee_id, :NEW.user_id as user_id 
         from employment_table e 
         inner join company_table c 
          on c.user_id = e.user_id 
         where e.user_id = :NEW.user_id 
          and e.emp_type = 'INT' 
          and c.company_id = '10200') S 
ON (out.user_id =S.user_id) 
WHEN MATCHED THEN UPDATE SET 
    out.employee_id = s.employee_id, 
    out.absence_reason = :NEW.absence_reason, 
    out.user_id = :NEW.user_id 
WHEN NOT MATCHED THEN 
    insert (absence_reason, employee_id) 
    values (:NEW.absence_reason, S.employee_id); 
+0

最後兩行:不應該是INSERT(o.absence_reason,o.employee_id)VALUES(:NEW.absence_reason,S.employee_id)? 因爲當我嘗試用自己的方式,我得到「ORA-000926遺漏值關鍵字」錯誤 – Jaanna

+0

肯定的是,你是對的:) –

+0

THX,應該讓我去:-) – Jaanna