需要帮助将 JSON 列转换为 SQL table

Need help in converting JSON column into SQL table

需要帮助将 JSON 列转换为 SQL 服务器 table。

我有一个 SQL 服务器 nvarchar(max) 列存储 JSON 格式值,如下所示。

我想将数据转换为 table 格式以生成一些报告。

请检查示例数据以及预期结果。

CREATE TABLE ##TempTable
(
    rawdata nvarchar(max)
)

INSERT INTO ##TempTable (rawdata) 
VALUES (
'[
    [
    {"key":"ID","value":"123"},
    {"key":"Name","value":"abc"},
    {"key":"Program","value":"qew"},
    {"key":"Type","value":"tyu"},
    {"key":"Section","value":"dd"},
    {"key":"Director","value":"ghghjg"},
    {"key":"Project","value":"hkhjk"},
    {"key":"Manager","value":"fghfgf"},
    {"key":"PCM","value":"gnhghj"},
    {"key":"Contractor","value":"gghgh"},
    {"key":"Client","value":"gghhg"}
    ],
    [
    {"key":"ID","value":"456"},
    {"key":"Name","value":"yui"},
    {"key":"Program","value":"gdffgf"},
    {"key":"Type","value":"ghgfjhjhj"},
    {"key":"Section","value":"jkjlkll"},
    {"key":"Director","value":"uiop"},
    {"key":"Project","value":"rtyuui"},
    {"key":"Manager","value":"rfv"},
    {"key":"PCM","value":"ujmk"},
    {"key":"Contractor","value":"rfvtg"},
    {"key":"Client","value":"efgg"}
    ]
]'
)

预期结果:

ID Name Program Type Section Director Project Manager PCM Contractor Client
123 abc qew tyu dd ghghjg hkhjk fghfgf gnhghj gghgh gghhg
456 yui gdffgf ghgf jkjlkll uiop rtyuui rfv ujmk rfvtg efgg

提前致谢。

如有任何帮助,我们将不胜感激。

您有双重嵌套的 JSON 数组。

第一级包含整个 key/value 对数组,表示最终结果中的一行。我们可以用OPENJSON打散数组,APPLY回到原来的table.

第二级有 key/value 对,其中包含列名称和值。我们需要在另一个 APPLY.

中进行调整
SELECT j2.*
FROM TempTable t
CROSS APPLY OPENJSON(t.rawdata) j1
CROSS APPLY (
    SELECT *
    FROM OPENJSON(j1.value)
      WITH (
        [key] varchar(50),
        value varchar(100)
      ) j2
    PIVOT (
        MAX(value) FOR [key] IN (
          ID,Name,Program,[Type],Section,Director,Project,Manager,PCM,Contractor,Client
        )
    ) pvt
) j2

SQL Fiddle