2013-04-20 76 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