如何使用JSON_MODIFY更新JSON的一部分

时间:2019-08-16 10:42:36

标签: sql-server spring-data-jpa

我将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);

客户是表名 configJSON是列名。

1 个答案:

答案 0 :(得分:0)

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

表格:

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