You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL仅更新指定字段的惯用方法 可选参数UPDATE实现咨询

解决方案

方案1:修改原有存储函数,增加空值判断

首先将函数入参设置默认值为NULL,UPDATE时仅当入参非空时覆盖原值:

create or replace
function update_author(target_id uuid, i_first_name varchar(50) default null, i_last_name varchar(50) default null)
returns json
language plpgsql
as
$$
declare inserted_author authors%rowtype;
begin
     update authors a
     set first_name = coalesce(i_first_name, a.first_name),
          last_name = coalesce(i_last_name, a.last_name)
     where a.id = target_id
     returning * into inserted_author;

return row_to_json(inserted_author);
end;
$$;

注意:如果你的业务需要支持显式将字段更新为NULL,该方案不适用,可以选择方案2。

方案2:使用JSONB作为入参(更灵活,推荐)

直接接收请求体的JSON作为参数,动态解析需要更新的字段,后续新增字段无需修改函数参数:

create or replace
function update_author(target_id uuid, update_data jsonb)
returns json
language plpgsql
as
$$
declare inserted_author authors%rowtype;
begin
     update authors a
     set 
       first_name = case when update_data ? 'first_name' then update_data->>'first_name' else a.first_name end,
       last_name = case when update_data ? 'last_name' then update_data->>'last_name' else a.last_name end
     where a.id = target_id
     returning * into inserted_author;

return row_to_json(inserted_author);
end;
$$;

调用时直接把完整请求体作为update_data参数传入即可,函数会自动判断请求中存在的字段进行更新,不存在的字段保留原值,也支持显式传入NULL覆盖原有值。

额外优化建议

HTTP协议中PUT方法语义为全量替换资源,部分更新建议使用PATCH方法,更符合REST规范。

内容的提问来源于stack exchange,提问作者thecashewtrader

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 15:27:01