简体   繁体   English

Postgresql用变量更新json数据

[英]Postgresql update json data with variables

I am trying to perform an update with a cursor variable in a previous step, but in a jsonb field, the system returns an error.我试图在上一步中使用游标变量执行更新,但在 jsonb 字段中,系统返回错误。 Contend field is a jsonb type.竞争字段是 jsonb 类型。 I am doing it as follows:我这样做如下:

¿Can you help me please?你能帮我吗?

Update OPTION 1更新选项 1

update test
set
content = jsonb_set(content, '{supplier}', '' || supplierId || ''::jsonb)
where operation_type = 'DEL';   

Error OPTION 1错误选项 1

SQL Error [22P02]: ERROR: invalid input syntax for type json Detail: The input string ended unexpectedly. SQL 错误 [22P02]:错误:json 类型的输入语法无效详细信息:输入字符串意外结束。 Where: JSON data, line 1: PL/pgSQL function inline_code_block line 72 at SQL statement其中:JSON 数据,第 1 行:PL/pgSQL 函数 inline_code_block 第 72 行 SQL 语句

Update OPTION 2更新选项 2

update test
set
content = jsonb_set(content, '{supplier}', '"' || supplierId || '"'::jsonb)
where operation_type = 'DEL';   

Error OPTION 2错误选项 2

SQL Error [22P02]: ERROR: invalid input syntax for type json Detail: Token """ is invalid. Where: JSON data, line 1: " PL/pgSQL function inline_code_block line 72 at SQL statement SQL 错误 [22P02]:错误:json 类型的无效输入语法详细信息:令牌“””无效。其中:JSON 数据,第 1 行:“PL/pgSQL 函数 inline_code_block 第 72 行在 SQL 语句中

First, cast the integer column to text and then to jsonb首先,将整数列转换为text然后转换为jsonb

jsonb_set(content, '{supplier}',  
          supplierId  :: text :: jsonb)

DEMO 演示

Thank you very much for your help.非常感谢您的帮助。 For Strings works perfectly, but numeric values show an error message.对于字符串工作完美,但数值显示错误消息。

content = jsonb_set(content, '{supplier}', supplierId::numeric::jsonb)

Error: SQL Error [42846]: ERROR: cannot cast type numeric to jsonb Where: PL/pgSQL function inline_code_block line 65 at SQL statement错误:SQL 错误 [42846]:错误:无法将数字类型转换为 jsonb 其中:PL/pgSQL 函数 inline_code_block 第 65 行在 SQL 语句中

Is there another way to convert it?有没有其他方法可以转换它?

Example data:示例数据:

'{"supplier": 1,"name": "Josh", "supplierId":10}'

Thank you very much,非常感谢,

EDIT: I resolved with: content = jsonb_set(content, '{supplier}', supplierId::integer::text::jsonb)编辑:我解决了: content = jsonb_set(content, '{supplier}', supplyId::integer::text::jsonb)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM