3

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

1 Answer 1

5

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 *;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, it gave me the right direction!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.