SQL Server:用一种条件更新五列

时间:2018-07-31 12:10:53

标签: sql sql-server case

在一个表中,我有一个货币列。我必须从两列(例如:a,b)计算一个值,并根据货币更新五列(例如:e,f,g,h,i,j)之一。

我尝试了CASE之类的

CASE when currency = 'INR'
then a+b
else 0
end as e
CASE when currency = 'USD'
then a+b
else 0
end as f
CASE when currency = 'CAN'
then a+b
else 0
end as g
CASE when currency = 'EUR'
then a+b
else 0
end as h
CASE when currency = 'AUD'
then a+b
else 0
end as i

还有其他方法吗?

2 个答案:

答案 0 :(得分:3)

Update myTable
   set e = CASE when currency = 'INR' then a+b ELSE 0 end, 
       f = CASE when currency = 'USD' then a+b ELSE 0 end,
       g = CASE when currency = 'CAN' then a+b ELSE 0 end,
       h = CASE when currency = 'EUR' then a+b ELSE 0 end,
       i = CASE when currency = 'AUD' then a+b ELSE 0 end;

答案 1 :(得分:0)

伪代码如下所示。 NULL / 0值不包括在内。

    var result = a+b;
    var columnName;

    CASE
    WHEN currency = 'INR' THEN columnName = e,
    WHEN currency = 'USD' THEN columnName = f,
    .
    .

    WHEN currency = 'AUD' THEN columnName = j

    END


    **your update statement goes here with 'columnName' variable..**