我有一个查询,需要发送到SQL Server,并使用text
article1
article2
article3
article4
article5
article6
article7
将结果作为JSON返回。此查询可以包含一个或多个JOIN。
问题是我希望将结果作为一个简单的平面json返回,每列作为一列,但是FOR FOR JSON
自动将其嵌套(Duh),JSON AUTO
不适合,因为它使用了点语法,但我希望它完全忽略其中的任何一个。
当然,这可以很容易地在应用服务器上完成,但我非常希望在数据库中完成。
查询:
FOR JSON PATH
结果(用于1):
SELECT
[Product].[ProductName] AS [Product.ProductName],
[Category].[CategoryName] AS [Category.CategoryName],
[Supplier].[CompanyName] AS [Supplier.CompanyName]
FROM
[Products] AS [Product]
INNER JOIN [Categories] AS [Category] ON [Category].[CategoryID] = [Product].[CategoryID]
LEFT JOIN [Suppliers] AS [Supplier] ON [Supplier].[SupplierID] = [Product].[SupplierID]
FOR JSON AUTO
我正在寻找的结果:
[
{
"Product.ProductName":"Test prod",
"Category":[
{
"Category.CategoryName":"Condiments!!!",
"Supplier":[
{
"Supplier.CompanyName":"Exotic Liquids"
}
]
}
]
}
]
答案 0 :(得分:0)
工作解决方案:
WITH test_CTE
AS
(
SELECT
[Product].[ProductName] AS [Product.ProductName],
[Category].[CategoryName] AS [Category.CategoryName],
[Supplier].[CompanyName] AS [Supplier.CompanyName]
FROM
[Products] AS [Product]
INNER JOIN [Categories] AS [Category] ON [Category].[CategoryID] = [Product].[CategoryID]
LEFT JOIN [Suppliers] AS [Supplier] ON [Supplier].[SupplierID] = [Product].[SupplierID]
)
SELECT * FROM test_CTE FOR JSON AUTO
答案 1 :(得分:0)
另一种仅以一对一关系进行的方法:
SELECT
[Product].[ProductName] AS [Product.ProductName],
(SELECT [Category].[CategoryName] FROM [Categories] WHERE [Category].[CategoryID] = [Product].[CategoryID]) AS [Category.CategoryName],
(SELECT [Supplier].[CompanyName] FROM [Suppliers] WHERE [Supplier].[SupplierID] = [Product].[SupplierID]) AS [Supplier.CompanyName]
FROM
[Products] AS [Product]
FOR JSON AUTO