您能帮我解决以下问题:
我有两张桌子
[sDocumentManagement]。[tDocuments]
[sDocumentManagement]。[tDocumentAttachments]
文档表中的每个条目都用于不同的文档,PK是DocumentID。在DocumentAttachments的表中,我们可以使用FK - DocumentID。
创建一个或多个附件我想要实现的目标如下。
[
{
DocumentID: 1,
Something: 'blb',
Attachments: [
{
AttachmentID: 1,
SomethingElse: '23232'
}
]
},
{
DocumentID: 2,
Something: 'blb',
Attachments: [
{
AttachmentID: 12,
SomethingElse: '23232'
},
{
AttachmentID: 13,
SomethingElse: '23232'
}
]
}
]
我想从两个表中获取所有信息。
我尝试了以下查询
SELECT @DocumentsJSON = (
SELECT *
FROM [sDocumentManagement].[tDocuments]
LEFT JOIN [sDocumentManagement].[tDocumentAttachments] ON [tDocuments].DocumentID = [tDocumentAttachments].DocumentID
FOR JSON PATH
)
SELECT @DocumentsJSON = (
SELECT
(
SELECT *
FROM [sDocumentManagement].[tDocumentAttachments]
WHERE [tDocumentAttachments].DocumentID = [tDocuments].DocumentID
FOR JSON PATH
) Attachments
, *
FROM [sDocumentManagement].[tDocuments]
FOR JSON PATH
)
答案 0 :(得分:0)
好的,我找到了解决方案:
SELECT @DocumentsJSON = (
SELECT *,
(
SELECT * FROM [sDocumentManagement].[tDocumentAttachments] ATTACHMENTS
WHERE ATTACHMENTS.DocumentID = DOCS.DocumentID
FOR JSON AUTO
) DocumentAttachments
FROM [sDocumentManagement].[tDocuments] DOCS
WHERE DOCS.OrganizationID = @OrganizationID
FOR JSON PATH, ROOT('Documents')
)
但还有另一个问题。
无论我宣布@DocumentsJSON NVarChar(MAX)输出, SQL只返回DocumentsJSON的4500个字符? 知道问题在哪里吗?