将每个员工的员工详细信息作为JSON数组返回给SQL Server中的每个员工

时间:2019-10-25 11:15:44

标签: json sql-server

我想从SQL Server作为JSON对象返回查询结果。我下面有Employee和EmployeeDtl表。

DROP TABLE IF EXISTS #Employee
CREATE TABLE #Employee (EmpId bigint, EmpName varchar(2000))

INSERT INTO #Employee VALUES (1, 'A')

DROP TABLE IF EXISTS #EmployeeDtl
CREATE TABLE #EmployeeDtl (EmpId bigint, WorkObject varchar(100), LocationName varchar(100))

INSERT INTO #EmployeeDtl VALUES (1, 'AAA', 'AAAAA')
INSERT INTO #EmployeeDtl VALUES (1, 'BBB', 'BBBB')
INSERT INTO #EmployeeDtl VALUES (1, 'CCC', 'CCCC')

我想以以下格式返回数据。

{
    "Employees": [{
        "EmpId": 1,
        "EmpName": "A",
        "EmpDtl": [{
                "WorkObject": "AAA",
                "LocationName": "AAAAA"
            },
            {
                "WorkObject": "BBB",
                "LocationName": "BBBB"
            },
            {
                "WorkObject": "CCC",
                "LocationName": "CCCC"
            }
        ]
    }]
}

我写了下面的查询。

SELECT 
    E.EmpId, E.EmpName, ED.WorkObject AS [EmpDtl.WorkObject], ED.LocationName AS [EmpDtl.LocationName]
FROM
    #Employee E 
    INNER JOIN #EmployeeDtl ED ON E.EmpId = ED.EmpId
FOR
    JSON PATH, ROOT('Employees')

但是,以上查询返回的是以下格式的数据。

{
    "Employees": [{
        "EmpId": 1,
        "EmpName": "A",
        "EmpDtl": {
            "WorkObject": "AAA",
            "LocationName": "AAAAA"
        }
    }, {
        "EmpId": 1,
        "EmpName": "A",
        "EmpDtl": {
            "WorkObject": "BBB",
            "LocationName": "BBBB"
        }
    }, {
        "EmpId": 1,
        "EmpName": "A",
        "EmpDtl": {
            "WorkObject": "CCC",
            "LocationName": "CCCC"
        }
    }]
}

您能帮我了解我在这里做错什么吗?

1 个答案:

答案 0 :(得分:3)

您需要将#EmployeeDtl嵌套为子查询:

SELECT E.EmpId,
       E.EmpName,
       (SELECT ED.WorkObject AS [WorkObject],
               ED.LocationName AS [LocationName]
        FROM #EmployeeDtl ED
        WHERE ED.EmpId = E.EmpId
        FOR JSON PATH) AS EmpDtl
FROM #Employee E
FOR JSON PATH, ROOT('Employees');

输出:

{
     "Employees": [
          {
               "EmpId": 1,
               "EmpName": "A",
               "EmpDtl": [
                    {
                         "WorkObject": "AAA",
                         "LocationName": "AAAAA"
                    },
                    {
                         "WorkObject": "BBB",
                         "LocationName": "BBBB"
                    },
                    {
                         "WorkObject": "CCC",
                         "LocationName": "CCCC"
                    }
               ]
          }
     ]
}