简体   繁体   中英

Dynamic values in JSON array query

I have a common table expression query like this.

;WITH Orders AS (
                    SELECT  OrderStatus,
                            OrderID,
                            OrderedBy,
                            OrderItems
                    FROM    Orders
                    WHERE   StudentGuid = @StudentGuid
                  )

The desired JSON array output should look like this.

[
 {
  "status":"Accepted",
  "orders":[
     {
        "OrderID":"100-1000",
        "OrderedBy":"John Smith"
     },
     {
        "OrderID":"100-1001",
        "OrderedBy":"John Smith"
     }
  ]
},
{
  "status":"Rejected",
  "orders":[
     {
        "OrderID":"100-1002",
        "OrderedBy":"John Smith"
     }
  ]
}
]

My current query is;

SELECT CAST((
                SELECT * 
                FROM (
                        SELECT (SELECT 'Accepted') AS [OrderStatus],
                               (SELECT CAST((
                                            SELECT OrderID,
                                                   OrderedBy,
                                            FROM    Orders
                                            WHERE   [OrderStatus] = 'Accepted'
                                            FOR JSON PATH
                                            ) AS NVARCHAR(MAX))) AS Orders
                        UNION       
                        SELECT (SELECT 'Rejected') AS [OrderStatus],
                               (SELECT CAST((
                                            SELECT OrderID,
                                                   OrderedBy,
                                            FROM    Orders
                                            WHERE   [OrderStatus] = 'Rejected'
                                            FOR JSON PATH
                                            ) AS NVARCHAR(MAX))) AS Orders
                ) AS Temp FOR JSON PATH ) AS NVARCHAR(MAX))

The problem with my query is it is not dynamic (as status are hard coded) and "orders node" in the final outcome fail to parse by JSON Formatters due to "unions."

How can I remove the hardcoding and make it dynamic with the CTE?

Thanks!

Looks like this can be done using subqueries.

    SELECT DISTINCT [status],
                    (SELECT orderID, 
                            orderedBy
                    FROM    Orders AS B
                    WHERE   [Status] = A.[Status]
                                FOR JSON PATH) AS Orders
    FROM Orders AS A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM