I need help to construct a TSQL query (SQL Server 2016) that can produce the following JSON structure.
The structure is as follows.The root is called "Agreement".
Each agreement got the main attributes AgreementDate, Position, OrganizationName. It is then followed by two sections "OrganizationDetails" and "OrganizationDetails2". All this is data in common for all agreements.
It ends with a section that can be different across the agreements. In the first agreement (below example) its called "AgreementType1" and for the second one its called "AgreementOfADifferentType". The last section can have different column setup as the data going into this section are stored in different tables.
Currently all in common data is stored in one single table. It includes data from column name "Agreement" down to "TypeOfOrganization2". The last dynamic section got data stored to different tables.
However these different tables can always be joined to the "in common table".
I would have no problem construction a TSQL query producing this if it wouldnt be for the last dynamic section of the JSON… Note that the dynamic sections can have different amount of columns, different names etc etc…
Any help is appreciated! 🙂
Example JSON
{"Agreement":
[
{
"AgreementDate": "2024-01-01",
"Position": "123",
"OrganisationName": "Hello",
"OrganisationDetails": {
"BusinessDate": "2024-01-01",
"TypeOfOrganization": 1
},
"OrganisationsDetails2": {
"BusinessDate2": "2024-01-01",
"TypeOfOrganization2": null
},
** "AgreementType1":** {
"DateOfRegistration": null,
"Amount": 884400.00
}
},
{
"AgreementDate": "2024-01-01",
"Position": "222",
"OrganisationName": "Hello2222",
"OrganisationDetails": {
"BusinessDate": "2024-02-02",
"TypeOfOrganization": 2
},
"OrganisationsDetails2": {
"BusinessDate2": "2024-05-01",
"TypeOfOrganization2": 5
},
**"AgreementOfADifferentType":** {
"Date": "2024-22-01",
"Date2": null,
"AmountOfSales": null,
"AmountOfSales2": 222.22
}
}
]
}
I have tried FOR JSON PATH but cant get it to work. I have also tried dynamic SQL trying to pieces together without success.
2
Answers
I have tried different types of writing the SQL. LEFT JOINS. Subqueries. Nothing works :) Above example that I first posted is my desired format. My problem is that the final part of the JSON gets mixed. Unfortunately I have to use "INCLUDE_NULL_VALUES". If I hadnt have to do that then everything would be fine...
i typed fast so it might not me exactly as you expected, but the key is PATRH you have to provide to JSON
output would be