繁体   English   中英

根据同一表中的列更新表中的行

[英]Update row in a table based on a column in the same table

如何根据同一表中列中的值更新表中的行?

表A:

 col1 col2 col3 total col_num
 NULL NULL NULL 100   1
 NULL NULL NULL 200   2
 NULL NULL NULL 300   3

更新后的结果:

表A:

col1  col2  col3 total col_num
100   NULL  NULL 100   1
NULL  200   NULL 200   2
NULL  NULL  300  300   3

除非您以某种方式动态地构造 SQL 语句,否则您不能一般地执行此操作。 但是,对于一组封闭的列,您可以使用一堆case表达式:

UPDATE tableA
SET col1 = CASE col_num WHEN 1 THEN total ELSE col1 END,
    col2 = CASE col_num WHEN 2 THEN total ELSE col2 END,
    col3 = CASE col_num WHEN 3 THEN total ELSE col3 END

您可以使用case表达式:

update tablea
set
    col1 = case when col_num = 1 then total end,
    col2 = case when col_num = 2 then total end,
    col3 = case when col_num = 3 then total end

您可能会包含一些逻辑来仅更新非空列

    update tablea
set
    col1 = case when col1 is null and col_num = 1 then total end,
    col2 = case when col2 is null and col_num = 2 then total end,
    col3 = case when col3 is null and col_num = 3 then total end
where
    (col1 is null and col_num = 1)
    or (col2 is null and col_num = 2)
    or (col3 is null and col_num = 3)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM