如何将嵌套的JSON导入SQL Server表?

时间:2018-11-28 22:39:44

标签: sql json sql-server tsql

我有一个嵌套的JSON变量(我在这里使用缩写),我想将其插入表中。我能够不嵌套列和值,但与嵌套部分的挣扎。我想要的是检索2行:sessionID = 20的另一行和30的子列的另一行。我正在使用SQL Server 2017。

DECLARE @json NVARCHAR(MAX)
SET @json =  
N'{
"List":
[
    {
    "ID": 13,
    "Date": "2015-12-07",
    "SessionID": {
      "20": {
        "discount": "no",
        "price": 15.99
            },
      "30": {
       "discount": "yes",
        "price": 12.99
            }
        }
    }
]
}'  



SELECT *  
FROM OPENJSON(@json, N'lax $.List')
WITH (ID int '$.ID' 
     ,[Date] date '$.Date'
     ,SessionID nvarchar(max) N'lax $.SessionID' AS JSON
     ) 

我想按以下方式检索数据。预先感谢您的帮助!

I would like retrieve query like this

1 个答案:

答案 0 :(得分:1)

正如Zohard Peled告诉您的那样,JSON的内部结构有待改进。通常,将数据放置为元素名称不是一个好主意。最好使用"SessionID":"20"之类的东西,而您的JSON带有"20"作为以下对象的名称。

尽管如此,可以使用key的{​​{1}}列来完成:

OPENJSON

-查询将逐步遍历您的结构:

DECLARE @json NVARCHAR(MAX)
SET @json =  
N'{
"List":
[
    {
    "ID": 13,
    "Date": "2015-12-07",
    "SessionID": {
      "20": {
        "discount": "no",
        "price": 15.99
            },
      "30": {
       "discount": "yes",
        "price": 12.99
            }
        }
    }
]
}'  

结果:

SELECT B.ID
      ,B.[Date]

      ,C.[key] AS SessionID --here's the magic...

      ,JSON_VALUE(C.[value],'$.discount') AS discount
      ,JSON_VALUE(C.[value],'$.price') AS price
FROM OPENJSON(@json)
WITH(List NVARCHAR(MAX) AS JSON) A --getting "List" as JSON
CROSS APPLY OPENJSON(A.List)
WITH(ID INT
    ,[Date] DATE
    ,SessionID NVARCHAR(MAX) AS JSON) B --getting "ID" and "Date" and "SessionID as JSON
CROSS APPLY OPENJSON(B.SessionID) C; --get the objects within the array, but nameless...