如果是,则更新sql查询以组合多个查询

时间:2017-07-20 22:08:06

标签: mysql sql sql-server

prod2中有空列finance 我想通过与prod2中的现有列product进行比较来填充finance列。我知道如何编写单个查询,但任何人都可以帮我写一个执行所有操作的查询。

update FINANCE
set prod2 = 'Vegetable'
where PRODUCT='VEG'

update FINANCE
set prod2 = 'Hot Dog'
where PRODUCT='HOT DOG'

update FINANCE
set prod2 = 'Cookie'
where PRODUCT='COOKIE'

update FINANCE
set prod2 = 'Other'
where PRODUCT= NULL

2 个答案:

答案 0 :(得分:1)

使用CASE EXPRESSION

UPDATE FINANCE
SET prod2 = CASE 
    WHEN PRODUCT='VEG'      THEN 'Vegetable'
    WHEN PRODUCT='HOT DOG'  THEN 'Hot Dog'
    WHEN PRODUCT='COOKIE'   THEN 'Cookie'
    WHEN PRODUCT IS NULL    THEN 'Other'
    ELSE prod2
END;

答案 1 :(得分:0)

CASE声明是您最好的选择:

update FINANCE
set prod2 = CASE 
    WHEN PRODUCT = 'VEG' 
        THEN 'Vegetable'
    WHEN PRODUCT = 'HOT DOG'
        THEN 'Hot Dog'
    WHEN PRODUCT = 'COOKIE'
        THEN 'Cookie'
    WHEN PRODUCT IS NULL
        THEN 'Other'
    -- Optional - just in case there is a value in Product that is not one of these values
    -- ELSE Product
END