首页 > 解决方案 > 在将记录集插入数据库之前,Postgres 将附加字段添加到数组中的 json 有效负载索引

问题描述

我正在 postgres 中创建一个存储过程,它接受一个 json 并通过执行 json_to_recordset 命令插入到表中。在使用该命令将记录集插入 SQL 表之前,我想添加一个附加字段作为 json 数组中 json 的索引。这可能吗?

对于数组中的每个索引,我想添加“current_status”:“pending”

[
    {
        "batch_id": "40",
        "state_id": "10"
    },
    {
        "batch_id": "40",
        "state_id": "10"
    }
]

[
    {
        "batch_id": "40",
        "state_id": "10",
        "current_status": "pending"
    },
    {
        "batch_id": "40",
        "state_id": "10"
        "current_status": "pending"
    }
]

另一种选择是事后更新表中唯一的新记录。我是 postgres 的新手,并且一直在阅读文档。

标签: postgresql

解决方案


根据您添加的评论,current_status = 'pending'应该将其作为插入的一部分添加到目标表中,而不是将密钥附加到 json 对象。

insert into target_table (batch_id, state_id, current_status)
select batch_id, state_id, 'pending' as current_status
  from json_to_recordset(<json>) as x(batch_id text, state_id text); 

推荐阅读