仅当列存在时才执行更新

Leo*_*ozo 4 postgresql dynamic-sql sql-update

如果列存在,是否可以有条件地执行更新?例如,我可能在表中有一个列,如果该列存在,我希望执行该更新,否则,只需跳过它(或捕获其异常)。

Cás*_*nan 5

您可以在函数内部执行此操作。如果您不想稍后使用该功能,您可以稍后将其删除。

要知道某个表中是否存在某列,您可以尝试使用information_schema.columns.

下面的查询创建了一个函数,该函数在表foo中搜索列,如果找到,则更新其值。稍后运行该函数,然后删除。

create function conditional_update() returns void as
$$
begin
  perform column_name from information_schema.columns where table_name= 'foo' and column_name = 'bar';
  if found then
    update foo set bar = 12345;
  end if;
end;
$$ language plpgsql;
select conditional_update();
drop function conditional_update();
Run Code Online (Sandbox Code Playgroud)