如果更新值为null不更新列(Don't update column if update v

2019-08-02 12:56发布

我有这样一个查询(在一个函数):

UPDATE some_table SET
  column_1 = param_1,
  column_2 = param_2,
  column_3 = param_3,
  column_4 = param_4,
  column_5 = param_5
WHERE id = some_id;

param_x是我的函数的参数。 有没有办法不更新这些列,为此参数是NULL ? 例如-如果param_4param_5NULL ,则仅更新前三列,离开旧值column_4column_5

我现在做的方法是:

SELECT * INTO temp_row FROM some_table WHERE id = some_id;

UPDATE some_table SET
  column_1 = COALESCE(param_1, temp_row.column_1),
  column_2 = COALESCE(param_2, temp_row.column_2),
  column_3 = COALESCE(param_3, temp_row.column_3),
  column_4 = COALESCE(param_4, temp_row.column_4),
  column_5 = COALESCE(param_5, temp_row.column_5)
WHERE id = some_id;

有没有更好的办法?

Answer 1:

掉落的SELECT语句,没有必要,只要使用的电流值:

UPDATE some_table SET
  column_1 = COALESCE(param_1, column_1),
  column_2 = COALESCE(param_2, column_2),
  column_3 = COALESCE(param_3, column_3),
  column_4 = COALESCE(param_4, column_4),
  column_5 = COALESCE(param_5, column_5)
WHERE id = some_id;


Answer 2:

巧妙的技巧,感谢Przemek,弗兰克 - 欧文!

我建议一个小修改,以欧文的回答,避免空更新。 如果任何参数为空(意为:“使用旧的价值”),该行是每即使行值没有改变(在第一次更新后)时更新。

通过添加“param_x IS NOT NULL”,我们避免了空更新:

UPDATE some_table SET
    column_1 = COALESCE(param_1, column_1),
    column_2 = COALESCE(param_2, column_2),
    ...
WHERE id = some_id
AND  (param_1 IS NOT NULL AND param_1 IS DISTINCT FROM column_1 OR
      param_2 IS NOT NULL AND param_2 IS DISTINCT FROM column_2 OR
     ...
 );


Answer 3:

此外,为了避免更新:

UPDATE some_table SET
  column_1 = COALESCE(param_1, column_1),
  column_2 = COALESCE(param_2, column_2)
  ...
WHERE id = some_id;
AND  (param_1 IS DISTINCT FROM column_1 OR
      param_2 IS DISTINCT FROM column_2 OR
      ...
     );

这是假设来定义目标列NOT NULL 。 否则,看到吉尔的扩展版本 。



文章来源: Don't update column if update value is null