如何在SQL中更新具有相同值或不同值的多个列?

Sak*_*idu 1 sql sql-update

我想更新表中具有相同值的多个列。例如,如果我们考虑这张表。

col1     col2
--------------
2        -99
-99        5
3          6
4        -99
Run Code Online (Sandbox Code Playgroud)

我想将表中的 -99 值更新为 NULL,预期结果如下所示。

col1     col2
--------------
2        NULL
NULL        5
3           6
4        NULL
Run Code Online (Sandbox Code Playgroud)

我正在使用这种方式。

update table_name set col1 = null where col1 = -99;
update table_name set col2 = null where col2 = -99;
Run Code Online (Sandbox Code Playgroud)

或者如果我想根据独特的条件更新列该怎么办?例如,第 1 列中为空的 -99 和第 2 列中为空的 5。

有没有办法通过一条语句来实现这一目标?提前致谢。

Dal*_*e K 5

您可以通过使用 case 表达式,但是有什么好处呢?

update table_name set
  col1 = case when col1 = -99 then null /* or any new value for col1 */ else col1 end
  , col2 = case when col2 = -99 then null /* or any new value for col2 */ else col2 end
where col1 = -99 or col2 = -99;
Run Code Online (Sandbox Code Playgroud)

请注意,正如 Larnu 所指出的,当您将列设置为 null 时,您可以将更新简化为:

update table_name set
  col1 = nullif(col1,-99)
  , col2 = nullif(col2,-99)
where col1 = -99 or col2 = -99;
Run Code Online (Sandbox Code Playgroud)

您可以将每列使用的值(-99)更改为您想要的任何值,例如col2 = 5

update table_name set
  col1 = nullif(col1,-99)
  , col2 = nullif(col2,5)
where col1 = -99 or col2 = 5;
Run Code Online (Sandbox Code Playgroud)