2013-04-20 107 views
0

我需要編寫一個幫助我清理下表的更新查詢的幫助。我一直在手動做每一行,這只是漫長而疲憊的過程。一次更新多行的SQL查詢

有沒有辦法編寫一次更新整個表的更新查詢。

The rules: 
1. All fields ending with m1 should only contain a value of 'aprn' 
2. All fields ending with m2 should only contain a value of 'pa' 
3. If 'pa' does exist in a field ending with m1 then that means that field should be NULL and the value 'pa' should be moved to the m2 column. 


table_a 
org_id org_name  a_m1 a_m2 b_m1  b_m2 
1  north  aprn pa  aprn  pa 
2  south  null null pa  null 
3  east  pa  null pa  null 
4  west  null pa  null  pa 


Correct: ORG_ID=1 (a_m1, a_m2, b_m1, b_m2) 
Correct: ORG_ID=4 (a_m1, a_m2, b_m1, b_m2) 
Correct: ORG_ID=2 (a_m1, a_m2) 

Incorrect: ORG_ID=2 (b_m1, b_m2) 
Incorrect: ORG_ID=3 (a_m1, a_m2, b_m1, b_m2) 

回答

0
update table_a 
set 
a_m2 = case when a_m1 = 'pa' or a_m2 = 'pa' then 'pa' end 
, b_m2 = case when b_m1 = 'pa' or b_m2 = 'pa' then 'pa' end 
, a_m1 = case when a_m1 = 'aprn' then a_m1 end 
, b_m1 = case when b_m1 = 'aprn' then b_m1 end 

SQL Fiddle with demo

它當然適用於您的數據集。如果這不適合你,請爲你的問題添加更多細節。

+0

感謝...我認爲這是有幫助的。 – user1991499 2013-04-21 15:50:36

+0

不客氣,@ user1991499。如果您發現有幫助的答案,請考慮提升和/或將其設置爲接受的答案。 – 2013-04-21 18:24:46

0

如果我正確理解你的問題,我懷疑多個更新語句可能是最好的。我喜歡用改變數據的語句來處理它們之一是簡單的。我更喜歡寫多個語句,讓RDBMS做更多的工作,更慢些,但總是正確的。從錯誤的數據更改中恢復很難。

我不知道我完全理解你的標準,但像下面這樣。如果我理解正確,你是否需要在1.和2.之前運行3.?

  1. update table_a 
        set a_m1 = 'aprn' 
    where a_m1 = 'pa'; 
    
  2. update table_a 
        set a_m2 = 'pa' 
    where a_m2 = 'aprn'; 
    
  3. update table_a 
        set a_m1 = NULL 
        set a_m2 = 'pa' 
    where a_m1 = 'pa'; 
    
    update table_a 
        set b_m1 = NULL 
        set b_m2 = 'pa' 
    where b_m1 = 'pa'; 
    
+0

@Andry ..謝謝,這與我一直在做的事情類似,我希望能夠加快速度,但我認爲處理數據清理並不總是很快捷。 – user1991499 2013-04-21 15:52:43