I have created a PostgreSQL function and it is receiving jsonb as an argument and want to extract value from jsonb and save it to db.
function:
CREATE OR REPLACE FUNCTION public.insertorupdatevendorcontactnos(
contactnos jsonb)
RETURNS TABLE(vendorhistory_id bigint, vendor_id bigint)
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
AS $BODY$
BEGIN
insert into vendorcontactnos (vendorid, key, value, createdby, createdon)
select (contactnos->>'vendorid') :: bigint,
(x->>'key')::integer,
x->>'value',
(contactnos->>'createdby') :: integer,
NOW()
from jsonb_array_elements(contactnos ->'items') as x;
INSERT INTO public.vendorcontactnoshistory( vendorid, vendorhistoryid, key, value, createdby, createdon)
select (contactnos->>'vendorid') :: bigint,
(contactnos->>'vendorhistoryid') :: bigint,
(x->>'key')::integer,
x->>'value',
(contactnos->>'createdby') :: integer,
NOW()
from jsonb_array_elements(contactnos ->'items') as x;
RETURN QUERY (select (contactnos->>'vendorid') :: bigint,
(contactnos->>'vendorhistoryid') :: bigint);
END;
$BODY$;
calling as
select * from insertorupdatevendorcontactnos('[{"vendorid":100,
"vendorhistoryid":1,
"createdby":5,
"items":[
{"key":1, "value":"+19876543210"},
{"key":2, "value":"+16543219870"},
{"key":3, "value":"+13210654987"}
]}]');
I need vendorcontactnos table output as below:
id vendorid key value createdby createdon
1 100 1 +19876543210 5 current date time
2 100 2 +16543219870 5 current date time
3 100 3 +13210654987 5 current date time
It is not extracting vendorid and createdby json values and saving it to DB table.
So, I was passing an json array in the function calling and I was expecting json in the function. removed square brackets of an json array, passing only json worked for me.
select * from insertorupdatevendorcontactnos('{"vendorid":1,
"vendorhistoryid":1,
"createdby":1,
"items":[
{"key":1, "value":"+19876543210"},
{"key":2, "value":"+16543219870"},
{"key":3, "value":"+13210654987"}
]}');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.