使用 SQL 查询将一列值更新为另一列值

Update one column value with another column value using SQL Query

我有一个 table,它包含三列整数值。在前两列中,我有一些值。现在我需要用其他两列中的最小值更新第三列。
我试过使用

update table set col3 = (SELECT CASE WHEN (col2 is null OR col1 < col2 )
THEN col1
ELSE col2
END AS col3
FROM  table 
WHERE col1 is not null or col2 is not null)`.  

但我收到如下错误:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

您可以使用 LEAST 来更新:

UPDATE mytable 
SET col3 = LEAST(COALESCE(col1, col2), COALESCE(col2, col1))
WHERE col1 IS NOT NULL OR col2 IS NOT NULL

您无需查询 table table 即可获得 col2col1 值。您可以直接在 UPDATE 查询的 SET 部分使用它们。

注: COALESCE用于处理NULL值。如果 col1col2 都是 NULL 那么 col3 也设置为 NULL.

在SQL服务器中你可以使用:

UPDATE mytable 
SET col3 = CASE 
              WHEN col2 IS NULL OR col1 < col2 THEN col1 
              ELSE col2
           END
WHERE col1 IS NOT NULL OR col2 IS NOT NULL

在 SQL Server 2012 或更高版本中,您可以使用 IIF:

UPDATE mytable 
SET col3 = IIF(col2 IS NULL OR col1 < col2, col1, col2)
WHERE col1 IS NOT NULL OR col2 IS NOT NULL

Demo here

您不需要自己加入 table,您可以在同一查询中使用来自列的数据

update table
set col3 = CASE WHEN (col2 is null OR col1 < col2 )
           THEN col1 ELSE col2 END  
WHERE col1 is not null or col2 is not null

您的查询的问题是您使用的是相关查询,它选择了 col1 和 col2(这基本上没问题,但不是必需的)并且您没有过滤结果(要采用哪个 col1、col2?)所以您要更新的每个 col3 都有一个 'bunch' 的其他值,而您只能有 1 个。如果您希望查询有效,您所要做的就是添加一个关系条件。