我正在尝试编写一个简单的plsql脚本以在表中插入数据,该表以jsonb作为列之一
示例:
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$;
但是执行此操作会出现错误:
ERROR: invalid input syntax for type json
LINE 11: '[{"specCode": {"name": "Telephone Number", "text": "TEL_NUM...
^
DETAIL: Token "tel" is invalid.
如何编写pgSql以在JSONB元素内使用变量? 听起来像是一个简单的要求,但是我在任何地方都找不到语法或引用
答案 0 :(得分:1)
可能最简单的方法是只使用字符串连接:
( '[{"specCode": {"name": "Telephone Number", "text": "TEL_NUM"}, "specValue": {"code": null, "text":' || tel || '}}]')::json
如果tel始终是整数,那将起作用。否则,您将需要双引号:
( '[{"specCode": {"name": "Telephone Number", "text": "TEL_NUM"}, "specValue": {"code": null, "text":"' || tel || '"}}]')::json
有些不相关,但这确实不需要pl / pgsql,并且绝对不需要循环。您可以使用generate_series来获取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 *;