gpt4 book ai didi

SQL JSON_VALUE 选择父值

转载 作者:行者123 更新时间:2023-12-04 08:55:49 24 4
gpt4 key购买 nike

我有这个 JSON,我需要提取 2 个字符串

  • "properties" 的 child 在以逗号分隔的列中。
  • "title" 的 child 在以逗号分隔的列中。

  • 结果应该是
  • BoxTp, boxNo
  • Box Type, Box Number
  • {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "properties": {
    "BoxTp": {
    "title": "Box Type",
    "type": [
    "null",
    "string"
    ],
    "description": "Type"
    },
    "boxNo": {
    "title": "Box Number",
    "type": [
    "integer",
    "null"
    ],
    "description": "Box No.",
    "format": "int32"
    }
    }
    }

    最佳答案

    您只需要解析输入 JSON 并连接结果。当然,您需要 SQL Server 2016+ 才能使用内置的 JSON 支持和 SQL Server 2017+ 使用 STRING_AGG() 进行字符串聚合。 :

    DECLARE @json nvarchar(max) = N'{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "properties": {
    "BoxTp": {
    "title": "Box Type",
    "type": [
    "null",
    "string"
    ],
    "description": "Type"
    },
    "boxNo": {
    "title": "Box Number",
    "type": [
    "integer",
    "null"
    ],
    "description": "Box No.",
    "format": "int32"
    }
    }
    }'

    SELECT STRING_AGG([key], ', ') AS ChildsOfProperties
    FROM OPENJSON(@json, '$.properties')

    SELECT STRING_AGG(j2.title, ', ') AS ChildsOfTitles
    FROM OPENJSON(@json, '$.properties') j1
    OUTER APPLY OPENJSON(j1.[value]) WITH (title nvarchar(100) '$.title') j2
    结果:
    ChildsOfProperties
    -----------------
    BoxTp, boxNo

    ChildsOfTitles
    --------------------
    Box Type, Box Number
    如果您需要单个语句:
    SELECT 
    STRING_AGG(j1.[key], ', ') AS ChildSOfProperties,
    STRING_AGG(j2.title, ', ') AS ChildSOfTitles
    FROM OPENJSON(@json, '$.properties') j1
    OUTER APPLY OPENJSON(j1.[value]) WITH (title nvarchar(100) '$.title') j2

    关于SQL JSON_VALUE 选择父值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63842761/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com