代码之家  ›  专栏  ›  技术社区  ›  Jebin

从openjson SQL Server 2016中的嵌套数组中删除对象

  •  4
  • Jebin  · 技术社区  · 8 年前

    我想删除 "AttributeName" : "Manufacturer" 来自SQL Server 2016中的以下json:

    declare @json nvarchar(max) = '[{"Type":"G","GroupBy":[],
    "Attributes":[{"AttributeName":"Class Designation / Compressive Strength"},{"AttributeName":"Size"},{"AttributeName":"Manufacturer"}]}]'
    

    这是我尝试的查询,但不起作用

    select JSON_MODIFY((
    select JSON_Query(@json, '$[0].Attributes') as res),'$.AttributeName.Manufacturer', null) 
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Ivan Sivak    8 年前

    以下是使用 for json open json . 重点是:

    1. 确定要删除的项目并用其替换 NULL JSON_MODIFY(@json,'$[0].Attributes[2]', null) . 我们只是说,把第二个元素 Attributes 并将其替换为null

    2. 将此数组转换为行集。我们需要设法摆脱这个 null 元素,这是我们可以在SQL中轻松过滤的内容 where [value] is not null

    3. 将其全部组装回原始JSON。由完成 FOR JSON AUTO

    请记住此类JSON数据转换的一个重要方面:

    JSON设计用于信息交换或最终存储信息。但您应该避免在SQL级别进行更复杂的数据操作。

    无论如何,这里的解决方案是:

    declare @json nvarchar(max) = '[{"Type": "G","GroupBy": [],"Attributes": [{"AttributeName": "Class Designation / Compressive Strength"}, {"AttributeName": "Size"}, {"AttributeName": "Manufacturer"}]}]';            
    
    with src as
    (
        SELECT * FROM OPENJSON(
            JSON_Query(
                JSON_MODIFY(@json,'$[0].Attributes[2]', null) , '$[0].Attributes'))
    )
    select JSON_MODIFY(@json,'$[0].Attributes', (
        select JSON_VALUE([value], '$.AttributeName') as [AttributeName] from src
        where [value] is not null
        FOR JSON AUTO 
    ))