CREATE PROCEDURE GetOrders
AS
BEGIN
SELECT o.OrderID, c.CompanyName,
(SELECT ProductID, ProductName, Quantity, UnitPrice
FROM [Order Details] od
JOIN Products p ON od.ProductID = p.ProductID
WHERE od.OrderID = o.OrderID
FOR JSON PATH) AS Products
FROM Orders o
JOIN Customers c ON o.CustomerID = c.CustomerID
FOR JSON PATH, ROOT('orders')
END
该存储过程将返回以下JSON格式的数据:
{
"orders": [
{
"OrderID": 10248,
"CompanyName": "Vins et alcools Chevalier",
"Products": [
{
"ProductID": 11,
"ProductName": "Queso Cabrales",
"Quantity": 12,
"UnitPrice": 14
},
{
"ProductID": 42,
"ProductName": "Singaporean Hokkien Fried Mee",
"Quantity": 10,
"UnitPrice": 9.8
},
{
"ProductID": 72,
"ProductName": "Mozzarella di Giovanni",
"Quantity": 5,
"UnitPrice": 34.8
}
]
},
{
"OrderID": 10249,
"CompanyName": "Toms Spezialitaten",
"Products": [
{
"ProductID": 14,
"ProductName": "Tofu",
"Quantity": 9,
"UnitPrice": 18.6
},
{
"ProductID": 51,
"ProductName": "Manjimup Dried Apples",
"Quantity": 40,
"UnitPrice": 42.4
}
]
}
]
}