【问题标题】:TSQL : Removing Square Brackets from JSON child propertyTSQL:从 JSON 子属性中删除方括号
【发布时间】:2020-04-28 19:49:36
【问题描述】:

我有以下 SQL 查询来创建 JSON。我使用WITHOUT_ARRAY_WRAPPER,所以根不会创建数组。

select *
from Documents D
join Notices Notice ON Notice.DocumentID = D.DocumentID
join NoticeDetails NoticeDetail on NoticeDetail.DocumentID = d.DocumentID
where d.DocumentID = 1234
FOR JSON Auto,WITHOUT_ARRAY_WRAPPER,INCLUDE_NULL_VALUES

上述查询生成以下 JSON。 (为简洁起见,我删除了一些 json 属性)

{
    "DocumentID": 1234,
    "ClientID": 3,  
    "Notice": [
        {
            "DocumentID": 1234,
            "StateCode": null,          
            "NoticeDetail": [
                {
                    "NoticeDetailID": 80122,
                    "DocumentID": 1234,                             
                    "CreatedDateTime": "2020-03-26T16:08:40.730",
                    "ModifiedDateTime": "2020-03-26T16:08:40.730"               
                }
            ]
        }
    ]
}

DocumentIDDocuments 表中的 PK 和 NoticesNoticeDetails 表中的 FK。也是 Notices 表中的唯一键。
所以基本上DocumentsNotices 是一对一的关系。所以我不希望 Notice 属性成为输出 json 中的数组。

我预期的输出 json 应该是

{
    "DocumentID": 1234,
    "ClientID": 3,  
    "Notice": 
        {
            "DocumentID": 1234,
            "StateCode": null,          
            "NoticeDetail": [
                {
                    "NoticeDetailID": 80122,
                    "DocumentID": 1234,                                         
                    "CreatedDateTime": "2020-03-26T16:08:40.730",
                    "ModifiedDateTime": "2020-03-26T16:08:40.730"               
                }
            ]
        }       
}

我的 SQL 应该是什么才能获得预期的输出?

【问题讨论】:

标签: tsql sql-server-2017 for-json


【解决方案1】:

我想我找到了。基于SO POST here

select *,
JSON_QUERY((
    SELECT *
    ,JSON_QUERY((
        SELECT * FROM NoticeDetails NoticeDetail
        WHERE NoticeDetail.DocumentID = D.DocumentID
        FOR JSON PATH
    )) AS NoticeDetail
    FROM Notices Notice
    WHERE Notice.DocumentID = d.DocumentID
    FOR JSON PATH,WITHOUT_ARRAY_WRAPPER
)) AS NOTICE
from Documents D
where d.DocumentID = 1234
FOR JSON PATH,WITHOUT_ARRAY_WRAPPER,INCLUDE_NULL_VALUES

【讨论】:

  • 拥有超过 15K 的声誉,您现在应该知道这个问题是重复的,应该关闭,而不是发布答案。
  • 为什么重要。 SO是否缺少空间?有时 SO 搜索不会返回您正在寻找的确切内容。在您发布之前,我也找到了自己的答案。
  • 是的,你已经在另一篇文章中找到了你的答案......没那么重要,这就是这个网站应该的工作方式......
猜你喜欢
  • 2013-11-11
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多