如何在同时更新多个列的同时为多列添加where子句?

时间:2011-09-02 08:34:08

标签: postgresql where-clause sql-update

我想同时更新10个以上的列,我的问题是我想为所有这些列添加where子句。

我的代码是:

UPDATE Customer AS c
                    SET 
                        name = a.name,
                        address= a.address,
                        telephone = a.telephone,
                        --
                        --
                        --


        FROM Customer a 
                      INNER JOIN 
                        ( SELECT casenumber
                               , max(currentDate) AS md 
                          FROM Customer 
                          GROUP BY casenumber
                        ) AS z 
                      ON  z.casenumber = a.casenumber
                      AND z.md = a.currentDate
                    WHERE (a.casenumber = c.casenumber)

在上面的语句中,我想添加条件,只有当它们不是0时才更新列。

例如,

UPDATE Customer AS C
    SET name = a.name,
    address= a.address,
    ...

    ..
     WHERE a.name <> 0,
            a.address <> 0, 
            a.telephone <> 0
            ....
            ...

是否有可能将条件放在检查每列?

任何建议都表示赞赏..

1 个答案:

答案 0 :(得分:2)

这样的事情(假设name <> 0是一个拼写错误而你的名字真的是字符列)

 UPDATE customer AS c
     SET name = CASE WHEN name <> '' THEN a.name ELSE name END,
         address = CASE WHEN address <> '' THEN a.address ELSE address END

如果列为空,这实质上会将列更新为当前值。

请注意,这不处理NULL值!如果您需要同等对待NULL和'',则需要使用coalesce(name, '')