Sql server 2008 一次更新多行的SQL查询

Sql server 2008 一次更新多行的SQL查询,sql-server-2008,Sql Server 2008,我需要帮助编写更新查询,帮助我清理下表。我一直在做每一行手动,这只是一个漫长而疲惫的过程 是否有一种方法可以编写一个更新查询,一次更新整个表 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 en

我需要帮助编写更新查询,帮助我清理下表。我一直在做每一行手动,这只是一个漫长而疲惫的过程

是否有一种方法可以编写一个更新查询,一次更新整个表

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)


它当然适用于您的数据集。如果这对您不起作用,请在您的问题中添加更多细节。

如果我正确理解您的问题,我怀疑多个更新语句可能是最好的。对于更改数据的语句,我喜欢做的一件事是使它们保持简单。我更喜欢写多条语句,让RDBMS做更多的工作,更慢,等等,但总是正确的。很难从错误的数据更改中恢复

我不确定我是否完全理解你的标准,但大致如下。如果我理解正确,您是否需要运行3。在1号之前。和2


  • @安德烈。。谢谢,这与我一直在做的事情类似,我希望能加快一点速度,但我想处理数据清理并不总是那么简单快捷。不客气,@user1991499。如果你发现有帮助的答案,请考虑投票和/或将其设置为可接受的答案。
    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
    
    update table_a
       set a_m1 = 'aprn'
     where a_m1 = 'pa';
    
    update table_a
       set a_m2 = 'pa'
     where a_m2 = 'aprn';
    
    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';