2014-03-06 79 views
0

我必須在過程中執行以下更新行。我可以在一行中更新它嗎?這裏只有一張桌子。多列更新

UPDATE magic_table SET first_col=0,last_col=my_value where first_col is not null; 
    UPDATE magic_table SET second_col=0,last_col=my_value where second_col is not null; 
    UPDATE magic_table SET third_col=null,last_col=my_value where third_col is not null; 

如果是這樣,它會給我們任何性能改進?

回答

2
update magig_table 
    set first_col = nvl2(first_col , 0, first_col), 
     second_col = nvl2(second_col, 0, second_col), 
     third_col = nvl2(third_col , 0, third_col), 
     last_col = my_value 
    where first_col is not null or 
     second_col is not null or 
     third_col is not null; 
+0

'third_col = nvl2(third_col,null,third_col),'是有效的嗎?如果我更新第三行,如'UPDATE magic_table SET third_col = null,last_col = my_value where third_col is not null;'?? – NaaN

0

試試這個:

update magig_table 
set first_col = case when first_col is not null then 0 end, 
    second_col = case when second_col is not null then 0 end, 
    third_col = null, 
    last_col = my_value 
where coalesce(first_col,second_col,third_col) is not null; 

這種方式是更好的性能則nvl2使用。第三列無論如何都是空的,所以沒有必要檢查它。

+0

1'或'在你的答案中是多餘的。你也可以告訴我,如果我更新第三行爲'UPDATE magic_table SET third_col = null,last_col = my_value where third_col不爲空;' – NaaN

+0

更新了答案;它被改寫,第一次我得到你的問題錯誤 – smnbbrv

+0

但是在行'coalesce ..''不一致的數據類型:期望CHAR獲得NUMBER'的行顯示錯誤。儘管'first_col'是varchar。 – NaaN