我正在尝试创建一个If Else SQL脚本来复制另一个表中的值,如果该列为null,它将从另一个表复制该值。
示例:
update table_name
set column_a = case
when column_a is null then copy value from other table
else null
end,
set column_b = case
when column_b is null then copy value from other table
end,
set column_c = case
when column_c is null then copy value from other table
end
where
table_d_column is null
答案 0 :(得分:4)
您的代码通常写为:
update t
set column_a = coalesce(t.column_a, ot.column_a),
column_b = coalesce(t.column_a, ot.column_b),
column_c = coalesce(t.column_a, ot.column_c)
from t join
othertable ot
on t.? = ot.?
where column_a is null or column_b is null or column_c is null;
注意:
update
只有一个`set子句。null
。join
的相应列应位于where
子句中。othertable
只有一行,则可以改为使用cross join
。