JSON 列在 SQL 中解析

JSON column parse in SQL

我数据库中的一列包含导入的 JSON 文件。

JSON的格式:

"result": true,
"data": {
    "3271012": {
        "taskId": 3271012,
        "opl": 1245,
        "owner": "name",
        "description": "note",
        "date": {
            "date": "2021-06-25 00:00:00.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note",
    },
    "3261201": {
        "taskId": 3261201,
        "opl": 1236,
        "owner": "name",
        "description": "note",
        "startDate": {
            "date": "2019-08-08 11:46:28.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note",

有数百个具有 taskId (3271012,3261201,...) 的对象,我如何将此任务从一列解析为多行?

预期输出:

首先,您可以获取所有“数据”项作为 key-value 与 OPENJSON 配对,然后提取感兴趣的值

DECLARE @s varchar(max) = 
'{"result": true,
"data": {
    "3271012": {
        "taskId": 3271012,
        "opl": 1245,
        "owner": "name",
        "description": "note",
        "date": {
            "date": "2021-06-25 00:00:00.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note"
    },
    "3261201": {
        "taskId": 3261201,
        "opl": 1236,
        "owner": "name",
        "description": "note",
        "startDate": {
            "date": "2019-08-08 11:46:28.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note"
     }
 }}';

select 
     json_value(d.value, '$.taskId')  taskid,
     json_value(d.value, '$.opl') opl,
     json_value(d.value, '$.owner') owner,
     cast (json_value(d.value, '$.startDate.date') as datetime2) dt2

from openjson (@s, '$.data') d; 

tabletbl(id,jsonstr)

也一样
 select t.id,
     json_value(d.value, '$.taskId')  taskid,
     json_value(d.value, '$.opl') opl,
     json_value(d.value, '$.owner') owner,
     cast (json_value(d.value, '$.startDate.date') as datetime2) dt2
from tbl t
cross apply openjson (jsonstr, '$.data') d;

db<>fiddle