我有以下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"
}
]
}
]
}
DocumentID
在Documents
表中为PK,在Notices
和NoticeDetails
表中为FK。也是Notices
表中的UNIQUE KEY。因此,基本上Documents
到Notices
是1到1的关系。所以我不希望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来获得预期的输出?
我想我找到了。基于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