在尚未设置时使用CASE进行更新

时间:2015-11-03 04:26:59

标签: sql-server-2008 case

我有一个简单的表格,如下所示:

+--------+-------+----------+
| client | value |  status  |
+--------+-------+----------+
| A      |    A1 | positive |
| B      |    B2 | neutral  |
| C      |    C3 | negative |
| D      |    B2 | neutral  |
| E      |    A1 | positive |
+--------+-------+----------+

状态字段直接与值字段相关,但是值字段会自动更改,因此我使用select语句来显示需要更新的状态字段,如下所示:

SELECT client, value, status, 
    CASE value 
        WHEN A1 THEN postive 
        WHEN B2 THEN neutral 
        ELSE negative 
    END AS new_status
FROM table
WHERE status <> CASE value 
                    WHEN A1 THEN postive 
                    WHEN B2 THEN neutral 
                    ELSE negative 
                END

这很好但我从来不喜欢SELECT和WHERE子句中出现的完全相同的CASE。是否有更好的方法来编写此SELECT以仅显示需要更新的状态字段?

1 个答案:

答案 0 :(得分:1)

使用子查询:

SELECT  *
FROM    (   
    SELECT  client,
            value,
            status,
            CASE value
            WHEN 'A1' THEN 'postive'
            WHEN 'B2' THEN 'neutral'
            ELSE 'negative'
            END AS new_status
    FROM    table                                                                                           
    ) AS t                                                                                              
WHERE   status <> new_status