是否有更好的方法来更新sql中的一个表的多个列

时间:2018-11-08 07:00:31

标签: sql sql-update

有更好的方法吗?

我必须update multiple columns如下表:

UPDATE tableA
       SET column1= '1234' WHERE column1 is NOT NULL;
UPDATE tableA
       SET column2= '1234' WHERE column2 is NOT NULL;
UPDATE tableA
        SET column3= '1234' WHERE column3 IS NOT NULL OR column3<>'0000';

4 个答案:

答案 0 :(得分:0)

您可以尝试以下操作

UPDATE tableA
       SET column1= '1234' ,         
        column2= '1234',
        column3= '1234'
  WHERE (column2 is NOT NULL and  column1 is NOT NULL)       
          and ( column3 IS NOT NULL OR column3<>'0000')

答案 1 :(得分:0)

您可以尝试使用CASE WHEN

UPDATE tableA
       SET column1= case when column1 is NOT NULL then '1234' end,
        column2= case when column2 is NOT NULL then '1234' end,
        column3= case when column3 is NOT NULL OR column3<>'0000' then '1234' end

答案 2 :(得分:0)

您可以执行以下操作,而不是3 updates

UPDATE tableA
       SET column1= CASE WHEN column1 is NOT NULL THEN '1234' END, 
       SET column2= CASE WHEN column2 is NOT NULL THEN '1234' END,
       SET column3= CASE WHEN column3 IS NOT NULL OR column3<>'0000' THEN '1234' END

答案 3 :(得分:0)

我认为您的最后一个条件实际上应该是column3 IS NOT NULL AND column3 <> '0000'OR将不包含第二个条件。

所以我想你想要

UPDATE tableA
    SET column1 = (CASE WHEN column1 IS NOT NULL THEN '1234' END),
        column2 = (CASE WHEN column2 IS NOT NULL THEN '1234' END),
        column3 = (CASE WHEN column3 IS NOT NULL AND column3 <> '0000' THEN '1234' END)

    WHERE (column1 IS NOT NULL) OR
          (column2 IS NOT NULL) OR
          (column3 IS NOT NULL AND column3 <> '0000');

WHERE子句不会影响结果集。仅在此处限制要更新的行数。