从 SQL 服务器获取 JSON 的分层数据

Get Hieararchical data as JSON from SQL Server

我关注table:

Id HieararchyId Name
1 / MHz
2 /1/ Finance
3 /1/ IT
4 /1/3/ Software Development
5 /1/3/ QA
6 /1/2/ Accountant

我想为我的 TreeView 获取数据,例如:

[
{
  "Id": 1,
  "HierarchyId": "/"
  "Name":"MHz",
  "Children":[
     {
        "Id": 3,
        "HierarchyId": "/1/"
        "Name":"IT",
        "Children":[
           {
              "Id": 4,
              "HierarchyId": "/1/3/"
              "Name":"Software Development",
              "Children":[]
           }
           {
              "Id": 5,
              "HierarchyId": "/1/3/"
              "Name":"QA",
              "Children":[]
           }
        ]
     },
     {
        "Id": 2,
        "HierarchyId": "/1/"
        "Name":"Finance",
        "Children":[
           {
              "Id": 6,
              "HierarchyId": "/1/2/"
              "Name":"Accountant",
              "Children":[]
           }
        ]
     }
   ]
 }
]

我试过这个:

得到错误

还是创建递归函数并在 client side 上填充 Tree 更好?

更新

CREATE FUNCTION dbo.GetJson (@departmentId hierarchyid)
RETURNS nvarchar(max)
AS BEGIN
RETURN (
    SELECT
      Id,
      HierarchyId,
      Name,
      children = JSON_QUERY(dbo.GetJson(HierarchyId))
    FROM Departments p
    WHERE p.HierarchyId.IsDescendantOf(@departmentId ) = 1
    FOR JSON PATH
);
END;

我发现最好的方法是使用递归函数。

您可以 self-join 所有节点并使用 GetAncestor

检查它们是否是子节点
CREATE FUNCTION dbo.GetJson (@parentID hierarchyid)
RETURNS nvarchar(max)
AS BEGIN
    RETURN (
        SELECT
          t.Id,
          t.HierarchyId,
          t.Name,
          children = JSON_QUERY(dbo.GetJson(t.HierarchyId))
        FROM Tree t
        WHERE t.HierarchyId <> @parentID
          AND t.HierarchyId.GetAncestor(1) = @parentID
        FOR JSON PATH
    );
END;

go
SELECT dbo.GetJson(hierarchyid::GetRoot());

db<>fiddle

结果

[
  {
    "Id": 1,
    "HierarchyId": "/1/",
    "Name": "MHz",
    "children": [
      {
        "Id": 2,
        "HierarchyId": "/1/2/",
        "Name": "Finance",
        "children": [
          {
            "Id": 6,
            "HierarchyId": "/1/2/6/",
            "Name": "Accountant"
          }
        ]
      },
      {
        "Id": 3,
        "HierarchyId": "/1/3/",
        "Name": "IT",
        "children": [
          {
            "Id": 4,
            "HierarchyId": "/1/3/4/",
            "Name": "Software Development"
          },
          {
            "Id": 5,
            "HierarchyId": "/1/3/5/",
            "Name": "QA"
          }
        ]
      }
    ]
  }
]