【发布时间】:2017-07-03 00:20:51
【问题描述】:
我有一个主表 Departments。详细信息表员工具有指向部门表的外键。当使用 PATH 选项将简单连接查询作为 JSON 返回时,它会为部门列出多行。而当使用 AUTO 选项时,它会返回唯一的部门,但我失去了对模式的控制。我怎样才能使用 PATH 选项,并且仍然能够像 AUTO 选项一样返回唯一部门。代码如下:
Declare @Departments as table (DeptName varchar(100), Location varchar(100) )
insert @Departments
select 'IT', 'San Francisco'
union
select 'Sales', 'Miami'
union
select 'Finance', 'NYC'
Declare @Employees as table (DeptName varchar(100) , EmployeeName varchar(100), Salary Decimal(7,2))
insert @Employees
select 'Finance', 'Ponzi', 1000
union
select 'Finance', 'Madoff', 10000
union
select 'IT' , 'Bill', 20000
union
select 'IT', 'Steve', 100
select D.DeptName [Department.Name], D.Location [Department.Location], E.EmployeeName [Employee.Name], E.Salary [Employee.Salary]
from
@Departments D
left join @Employees E on E.DeptName = D.DeptName
for JSON Auto
自动模式返回以下结果。注意每个部门只出现一次:
[{
"Department.Name": "Finance",
"Department.Location": "NYC",
"E": [{
"Employee.Name": "Madoff",
"Employee.Salary": 10000.00
}, {
"Employee.Name": "Ponzi",
"Employee.Salary": 1000.00
}
]
}, {
"Department.Name": "IT",
"Department.Location": "San Francisco",
"E": [{
"Employee.Name": "Bill",
"Employee.Salary": 20000.00
}, {
"Employee.Name": "Steve",
"Employee.Salary": 100.00
}
]
}, {
"Department.Name": "Sales",
"Department.Location": "Miami",
"E": [{}
]
}
]
PATH 选项返回以下结果。注意每个部门的多次出现:
[{
"Department": {
"Name": "Finance",
"Location": "NYC"
},
"Employee": {
"Name": "Madoff",
"Salary": 10000.00
}
}, {
"Department": {
"Name": "Finance",
"Location": "NYC"
},
"Employee": {
"Name": "Ponzi",
"Salary": 1000.00
}
}, {
"Department": {
"Name": "IT",
"Location": "San Francisco"
},
"Employee": {
"Name": "Bill",
"Salary": 20000.00
}
}, {
"Department": {
"Name": "IT",
"Location": "San Francisco"
},
"Employee": {
"Name": "Steve",
"Salary": 100.00
}
}, {
"Department": {
"Name": "Sales",
"Location": "Miami"
}
}
]
使用PATH模式如何防止部门多次出现?
【问题讨论】:
标签: sql-server json path sql-server-2016