首页 > 解决方案 > 如何使用 JSON_MODIFY 更新部分 json

问题描述

我使用 mssql 作为数据库并将所有详细信息存储为 json 字符串。

现在我想更新一个 json 对象的一部分。

怎么做?

下面是 json 对象。

{"customerName":"mohan","salesForceUrl":"erferf","notes":"ferfer","custId":"3bc5a660-c001-11e9-84a1-11b306ffa283","deleteInd":"N","createdDate":1565944718619,"lastUpdatedDate":null,"deletedDate":null,"feeds":[]}

当我想更新除作为数组的提要之外的所有内容时,如何做到这一点,我正在为此使用 JPA @Query。

@Modifying
    @Query(value="update Customers set configJSON = JSON_MODIFY(configJSON, '$.customerName', 'mohan') where CustomerId = ?1", nativeQuery=true)
    @Transactional
    public void updateCutomer(String custId);

Customers 是表名 configJSON 是列名。

标签: sql-serverspring-data-jpa

解决方案


$.feeds一种可能的方法是从当前提取部分,用这个部分JSON更新输入,最后用修改后的输入更新表:JSON$.feedsJSON

桌子:

CREATE TABLE Customers (
   customerId int,
   configJSON nvarchar(max)
)
INSERT INTO Customers
   (customerId, configJSON)
VALUES
   (1, N'{"customerName":"xxx", "custId":"3bc5a660-c001-11e9-84a1-11b306ffa283", "feeds":[{"a": 1}, {"b": 2}]}')

陈述:

DECLARE @json nvarchar(max) = N'{"customerName":"mohan","salesForceUrl":"erferf","notes":"ferfer","custId":"3bc5a660-c001-11e9-84a1-11b306ffa283","deleteInd":"N","createdDate":1565944718619,"lastUpdatedDate":null,"deletedDate":null,"feeds":[]}'
UPDATE Customers
SET configJSON = JSON_MODIFY(
   @json,
   '$.feeds',
   JSON_QUERY(configJSON, '$.feeds')
)
WHERE customerId = 1

推荐阅读