2014-03-05 37 views
0

我有如下一個表:插入基於另一列的值(的Oracle 11g)

TABLE_1 
{ 
Name varchar2(30) 
Value_a number 
Update_time timestamp 
} 

我想這取決於「value_a」的值的INSERT +合併過程中有條件地更新UPDATE_TIME的價值。如果value_a小於0.1,則檢查update_time是否爲空。如果是,那麼更新否則不。如果value_a大於0.1,則檢查update_time是否不爲空。如果是,則爲空。

我有一個我清楚的table_1_stage,然後插入所有數據,然後根據鍵匹配在表1中「合併或插入」。我正在使用oracle 11g。

我準備語句如下所示:" MERGE INTO " + TABLE_1 + " TABLE1 " + " USING TABLE_1_STAGE TABLE1S " + " ON (TABLE1.NAME = TABLE1S.NAME) " + " WHEN MATCHED THEN " + " UPDATE set VALUE_A = TABLE1S.VALUE_A " + " WHEN NOT MATCHED THEN " + " INSERT (NAME, VALUE_A) " + " VALUES (?, ?) "

的UPDATE_TIME列是新的,我需要設置/重置它取決於value_a。

我知道一個存儲過程可能是一個更好的調用,但我正在尋找是否可以在插入查詢中執行此操作?

+0

這是插入或更新,並且您使用Oracle 11g或Oracle 10g。你能否認可你的問題,使之與你試圖達到的一致? – Ben

+0

@Ben,完成!現在可以請你提出我能做些什麼? –

回答

2
Update table1 
set Update_time = (case when value_a < 0.1 and Update_time is null then sysdate 
         when value_a > 0.1 and Update_time is not null then null 
        else Update_time end); 

將sysdate更改爲所需的值。

編輯:

包括在合併聲明編輯。請參閱下面的查詢(未用真實數據測試) 這樣我們就不會在整個表上運行更新。

Merge into table1 t1 
using table1_staging t1s 
on t1.name = t1s.name 
when matched then 
update t1.value_a = t1s.value_a, 
t1.Update_time = (case when t1s.value_a < 0.1 and t1.Update_time is null then sysdate 
          when t1s.value_a > 0.1 and t1.Update_time is not null then null 
         else t1.Update_time end) 
when not matched then 
INSERT (name, values_a) 
    VALUES (t1s.name, t1s.values_a); 
+0

我的數據庫可能有10000行。插入完成後,「更新」語句是否有效?請看我編輯的帖子,因爲prev可能錯過了一些要點。 –

+0

謝謝jasti!我會試試這個。 –

+0

效果很好!非常感謝。 –

0

您的邏輯非常符合update聲明。我認爲這是你想要什麼:

update table1 
    set update_time = sysdate 
    where update_time is null and value_a < 0.1 or 
      update_time is not null and value_a > 0.1; 

要設置update_time到你不說什麼值。我認爲這是現在的時間。

+0

是的,update_time必須是「sysdate」。我的數據庫可能有10000行。插入完成後,「更新」語句是否有效?請看我編輯的帖子,因爲prev可能錯過了一些要點。 –

0

我的解決方案消除了更新整個表,這可能取決於你的數據有表現不佳:

update table1 set update_time = (
select case when value_a > 0.1 and update_time is not null then null when value_a < 0.1 and update_time is null then sysdate) where update_time is null and value_a < 0.1 or update_time is not null and value_a > 0.1; 
+0

我的數據庫可能有10000行。插入完成後,「更新」語句是否有效?請看我編輯的帖子,因爲prev可能錯過了一些要點。 –