从另一个表动态SQL Server附加到特定数组索引

时间:2018-04-05 23:24:26

标签: sql arrays json sql-server ssms-2016

我有一个需要修改的json字符串

{"RecordCount":3,"Top":10,"Skip":0,"SelectedSort":"Seed asc","value":[{"AccountProductListId":22091612871138,"Name":"April 4th 2018","AccountId":256813438078643,"IsPublic":false,"Comment":"Test order sheet","Quantity":3},{"AccountProductListId":166305848801939,"Name":"test","AccountId":256813438078643,"IsPublic":false,"Comment":"","Quantity":1},{"AccountProductListId":21177711287586,"Name":"Test Order sheet","AccountId":256813438078643,"IsPublic":true,"Comment":"the very first sheet","Quantity":2}]}

数组的内部值如下所示:

"value": [{
    "AccountProductListId": 22091612871138,
    "Name": "April 4th 2018",
    "IsPublic": false,
    "Comment": "Test order sheet",
    "Quantity": 3
}, {
    "AccountProductListId": 166305848801939,
    "Name": "test",
    "IsPublic": false,
    "Comment": "",
    "Quantity": 1
}, {
    "AccountProductListId": 21177711287586,
    "Name": "Test Order sheet",
    "IsPublic": true,
    "Comment": "the very first sheet",
    "Quantity": 2
}],

我需要做的是从另一个表中附加一些数据:

AccountProductListId    ProductID
21177711287586          97096131867163|32721319938943
22091612871138          97096131867163|145461009584740|130005306921282
166305848801939         8744071222157

正如您所看到的,AccountProductListId已经在JSON结果中,所以我应该知道它应该去哪个数组。唯一的问题是我不知道将ProductID数据合并到其特定数组索引的语法。 JSON数组可以包含3个以上的项目。

基本上以这样的结果结束:

    "value": [{
    "AccountProductListId": 22091612871138,
    "Name": "April 4th 2018",
    "IsPublic": false,
    "Comment": "Test order sheet",
    "Quantity": 3,
    "ProductID": "97096131867163|145461009584740|130005306921282"
}, {
    "AccountProductListId": 166305848801939,
    "Name": "test",
    "IsPublic": false,
    "Comment": "",
    "Quantity": 1,
    "ProductID": "8744071222157"
}, {
    "AccountProductListId": 21177711287586,
    "Name": "Test Order sheet",
    "IsPublic": true,
    "Comment": "the very first sheet",
    "Quantity": 2,
    "ProductID": "97096131867163|32721319938943"
}],

任何信息都将不胜感激。感谢。

1 个答案:

答案 0 :(得分:0)

使用SQL Server处理

在SQL Server 2016之前,没有内置的支持来读取或写入JSON。

启动SQL Server 2016,您可以使用OPENJSON行集函数读取JSON和FOR JSON子句来编写JSON。

请参阅https://docs.microsoft.com/en-us/sql/relational-databases/json/json-data-sql-server

方法是使用OPENJSON将JSON字符串作为行集读取,将其与表连接以拾取ProductID并使用FOR JSON转换回JSON。

在SQL Server外部进行处理

根据您的具体情况,在SQL Server外部解析JSON可能更简单。如果走那条路,你就可以

  1. 从已解析的JSON
  2. 中收集所有AccountProductListID
  3. 通过存储过程将收集的ID发送到SQL Server,该存储过程接收TVP输入并输出AccountProductListID - > ProductID映射
  4. 将ProductID注入JSON对象并序列化回字符串