如何使用声明的变量来创建一个json元素

问题描述 投票:0回答:1

我有一个存储过程,在这里,我声明了一个变量,它保存了一个select函数的值。我需要使用此值来创建一个json元素,但它会抛出异常

function jsonb_set(jsonb, unknown, character varying, boolean) does not exist

这是功能:

CREATE OR REPLACE FUNCTION test ( ) RETURNS 
INTEGER AS $$
DECLARE
intent varchar;
BEGIN  

select id into intent from customer;
UPDATE orders
SET data = jsonb_set(
data, 
'{Items}',      -- the array in which we operate
to_jsonb(
(WITH ar AS(
  WITH temp AS(
    SELECT data->'Items' AS items   -- the array in which we operate
    FROM orders
    WHERE id = 1    -- the filtered order we are updating
  )
  SELECT jsonb_set(
    jsonb_array_elements(items),
    '{Quantity}',   -- the new field we are adding
    intent,          -- this is where i need to replace the variable
    true)
  FROM temp)
 SELECT (array_agg(ar.jsonb_set))
 FROM ar)),
 false)
  WHERE id = 1;
return 0;

EXCEPTION WHEN others THEN

return 1;
END;
$$ LANGUAGE plpgsql;

复制我需要替换变量的代码段:

SELECT jsonb_set(
    jsonb_array_elements(items),
    '{Quantity}',   -- the new field we are adding
    intent,          -- this is where i need to replace the variable
    true)
json postgresql
1个回答
0
投票

你必须使用intentjsonb明确地将CAST(intent AS jsonb)施放到intent::jsonb

它与字符串文字一起使用的原因是这样的文字属于(内部)类型unknown,它可以转换为大多数其他类型,但character varyingjsonb之间没有隐式转换,所以你必须使用一个明确的。

© www.soinside.com 2019 - 2024. All rights reserved.