在postgresql中如何更改jsonb类型cloumn中的值?

时间:2016-12-29 07:49:40

标签: postgresql function postgresql-9.4

现在我想用postgresql函数来改变jsonb类型的cloumn值,现在我有一个函数实现类型json

CREATE OR REPLACE FUNCTION "json_object_set_key"(
  "json"          json,
  "key_to_set"    TEXT,
  "value_to_set"  anyelement
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT COALESCE(
  (SELECT ('{' || string_agg(to_json("key") || ':' || "value", ',') || '}')
     FROM (SELECT *
             FROM json_each("json")
            WHERE "key" <> "key_to_set"
            UNION ALL
           SELECT "key_to_set", to_json("value_to_set")) AS "fields"),
  '{}'
)::json
$function$;

但我无法将json类型更改为jsonb,现在我想要一个函数&#34; jsonb_object_set_key&#34;谁能实现,请帮助我,非常感谢你。

1 个答案:

答案 0 :(得分:-1)

只需更改返回数据类型:

t=# DROP FUNCTION jsonb_object_set_key(json,text,anyelement);
DROP FUNCTION
t=# CREATE OR REPLACE FUNCTION "jsonb_object_set_key"(
t(#       "jsonb"          jsonb,
t(#       "key_to_set"    TEXT,
t(#       "value_to_set"  anyelement
t(#     )
t-#       RETURNS jsonb
t-#       LANGUAGE sql
t-#       IMMUTABLE
t-#       STRICT
t-#     AS $function$
t$#     SELECT COALESCE(
t$#       (SELECT ('{' || string_agg(to_json("key") || ':' || "value", ',') || '}')
t$#          FROM (SELECT *
t$#                  FROM jsonb_each("jsonb")
t$#                 WHERE "key" <> "key_to_set"
t$#                 UNION ALL
t$#                SELECT "key_to_set", to_jsonb("value_to_set")) AS "fields"),
t$#       '{}'
t$#     )::jsonb
t$#     $function$;
CREATE FUNCTION

在这里:

t=# select pg_typeof(jsonb_object_set_key('{"a":3}','a',5));
 jsonb

如果你使用jsonb_sethttps://www.postgresql.org/docs/current/static/functions-json.html

至少有9.5个concider