0
我有一個主表部門。詳細信息表Employees中的外鍵指向Departments表。當使用PATH選項將簡單聯接查詢作爲JSON返回時,它將列出Department的多個行。而使用AUTO選項時,它將返回獨特的部門,但是我放棄了對模式的控制。我如何使用PATH選項,並仍然能夠像AUTO選項一樣返回唯一的部門。以下是代碼:防止SQL「FOR JSON」導致重複
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模式時防止多個部門出現?