【问题标题】:Postgres plpgsql JSON assignmentPostgres plpgsql JSON 赋值
【发布时间】:2016-02-08 17:38:26
【问题描述】:

我正在使用 Postgres 中的 JSONB,并试图了解如何正确执行对 plpgsql 中 JSON 属性的赋值。

这个查询 sn-p 报告了一个语法错误,因为赋值的前括号,但是我很确定这个语法是引用 plpgsq 中的 JSON 对象所必需的:

IF (NEW."data")->>'custom' IS NULL THEN
  (NEW."data")->>'custom' := 0;
END IF;

这是在 postgresql 触发器中,所以 NEW 是提供的与新数据库记录相关的变量。

有人可以建议将值分配给 JSON(B) 属性的正确技术是什么吗?

【问题讨论】:

  • 9.4...很快就会是 9.5。

标签: json postgresql plpgsql


【解决方案1】:

Postgres 9.5 中使用 jsonb_set() 函数非常简单:

if new.data->>'custom' is null then
    new.data = jsonb_set(new.data::jsonb, '{custom}', '0'::jsonb);
end if;

Postgres 9.4 中没有jsonb_set(),所以问题更复杂:

if new.data->>'custom' is null then
    new.data = (
        select json_object_agg(key, value)
        from (
            select key, value
            from jsonb_each(new.data)
            union
            values ('custom', '0'::jsonb)
        ) s
    );
end if;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 2012-08-08
    相关资源
    最近更新 更多