Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variable name in JSONB insert in postgres

I am trying to write a simple plsql script to insert data in a table, which has jsonb as one of the columns

Example:

do $do$ declare
tel varchar:= '8000012000';
begin for i in 1..10 loop insert
    into
        t_tbl_sample(
            lob,
            prop_name,
            prop_value,
            prop_details
        )
    values(
        'TN_ADD' || i,'ABC','XYZ',
        '[{"specCode": {"name": "Telephone Number", "text": "TEL_NUM"}, "specValue": {"code": null, "text": tel}}]'
    );
end loop;
end $do$;

But executing this gives an error:

ERROR:  invalid input syntax for type json
LINE 11:   '[{"specCode": {"name": "Telephone Number", "text": "TEL_NUM...
           ^
DETAIL:  Token "tel" is invalid.

How can i write the pgSql to use a variable inside the JSONB element? Sounds like a simple requirement , but I could not find the syntax or reference anywhere

like image 974
user1933888 Avatar asked Mar 12 '26 12:03

user1933888


1 Answers

Probably the easiest way is to just use string concatenation:

( '[{"specCode": {"name": "Telephone Number", "text": "TEL_NUM"}, "specValue": {"code": null, "text":' || tel || '}}]')::json

That will work if tel is always an integer. Otherwise, you will need double-quotes:

( '[{"specCode": {"name": "Telephone Number", "text": "TEL_NUM"}, "specValue": {"code": null, "text":"' || tel || '"}}]')::json

Somewhat unrelated, but this really doesn't require pl/pgsql and definitely doesn't require a loop. You can use generate_series to grab each element of tel:

WITH data AS (
  SELECT i, substr('8000012000', i, 1) as tel
  FROM generate_series(1, length('8000012000')) as g(i)
)
INSERT INTO 
        t_tbl_sample(
            lob,
            prop_name,
            prop_value,
            prop_details
        )
SELECT  'TN_ADD' || i,
        'ABC',
        'XYZ',
        ('[{"specCode": {"name": "Telephone Number", "text": "TEL_NUM"}, "specValue": {"code": null, "text":"' ||  tel || '"}}]')::json
FROM data
returning *;
like image 200
Jeremy Avatar answered Mar 15 '26 07:03

Jeremy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!