我正在使用下面的代碼創建一個帶有變數的函式,該函式使用 json 物件更新 jsonb 列,或者如果它不存在則創建它 - 在這篇文章的幫助下
但是我真的很難在 json 字串中插入變數 $2 和 $3 。有什么建議么?
CREATE OR REPLACE FUNCTION public.updateoffset(site text, offsetnumber integer, toscrape integer)
RETURNS void
LANGUAGE sql
AS $function$
update settings set "offset" = coalesce("offset", '{}') || '{"$2": {"toscrape":3$}}'
where site = $1;
$function$
uj5u.com熱心網友回復:
不要使用字串插值來構建 JSON 值 - 改用JSON 函式和運算子,特別是json_build_object:
update settings
set "offset" = coalesce("offset", '{}') || json_build_object($2, json_build_object('toscrape', $3))
where site = $1;
此外,使用起來可能更簡單json_set:
update settings
set "offset" = json_set(coalesce("offset", '{}'), ARRAY[$2::text,'toscrape'], $3)
where site = $1;
toscrape(但是,它確實將其他屬性保留在內部物件中,而不是用僅作為鍵的物件完全替換它)
uj5u.com熱心網友回復:
使用函式格式()。
...
update settings
set "offset" =
coalesce("offset", '{}') || format('{"%s": {"toscrape":%s}}', $2, $3)::jsonb
where site = $1;
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475233.html
標籤:sql PostgreSQL jsonb
上一篇:提高SQL查詢的運行時間
下一篇:按類別從表中選擇最大值
