【发布时间】:2019-07-09 11:55:16
【问题描述】:
我一直在尝试从三个表在 sql 中创建一个 json 对象
主表/实体是“订单”,其 id 为 addressId
并且进一步的地址表有countryId和stateId,它们是指
州表和国家表
orderTable
Id AddressId Status
1 1 Processed
AddressTable
Id countryId stateId FirstName LastName
1 5 7 John cena
countryTable
Id Name
5 usa
StateTable
Id Name
7 DC
输出应该如下所示
{
"firstName": "John",
"lastName": "cena",
"Country" : {
"name": "usa",
"id" : "5"
},
"States" : {
"name": "DC",
"id" : "7"
}
}
我曾尝试使用此查询并得到类似的结果,但我想从 json 中删除 [] [] 数组对象容器
[ // I want to remove this
{
"FirstName": "Steve",
"LastName": "Gates",
"country":
[ // I want to remove this
{
"name": "usa",
"id" : "5"
}
], // I want to remove this
"states" :
[ // I want to remove this
{
"name": "DC",
"id" : "7"
}
] // I want to remove this
根据微软的博客我们可以使用
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
但是如果我使用这个,那么它不包括国家和州作为单独的子对象 所以我使用了“FOR JSON AUTO”,它给了我想要的输出,但它还为每个 json 对象添加了方括号
这是我的查询
Select ord.*, (Select * from Address ad Left outer join Country country on country.Id = ad.CountryId
Left outer join State sp on sp.Id = ad.StateId where ad.Id = ord.AddressId FOR JSON AUTO) as AddressJson
, (Select * from Address ad Left outer join Country country on country.Id = ad.CountryId
Left outer join State sp on sp.Id = ad.StateId where ad.Id = ord.AddressId1 FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER) as AddressJson2
from [order] ord )
【问题讨论】:
标签: sql json sql-server sql-server-2016