I have some tables:
teste // id, descricao
teste2 // id, descricao
relacao // id, idTeste, idTeste2
With this structure, I got all products owned by a client. Now I'm trying to use FOR JSON PATH
to extract data from the database:
This is where I am at the moment:
SELECT
teste2.descricao AS "nome",
relacao.id AS "produto.id"
FROM teste2
INNER JOIN relacao ON relacao.idTeste2 = teste2.id
FOR JSON PATH
And this is the result from the server:
[{
"nome": "Raphael Schubert",
"produto": {
"id": 1
}
}, {
"nome": "Raphael Schubert",
"produto": {
"id": 2
}
}, {
"nome": "Lorraine Schubert",
"produto": {
"id": 3
}
}, {
"nome": "Lorraine Schubert",
"produto": {
"id": 4
}
}]
I was expecting to create a query where the answer is like this:
[{
"nome": "Raphael Schubert",
"produto": [{
"id": 1
}, {
"id": 2
}]
}, {
"nome": "Lorraine Schubert",
"produto": [{
"id": 3
}, {
"id": 4
}]
}]
I think with for each at select was possible, but I'm new to SQL Server, I know a bit about MySQL but was not able to extract that info.
Best Answer
As Martin Smith suggested in a comment the necessary syntax is very similar to
FOR XML
. Here is how I solved my problem:Result: