SQL Server-创建一个内部JSON查询以返回展平的值

时间:2018-11-23 18:53:31

标签: sql sql-server sql-server-2016

简化的表结构如下

CREATE TABLE TableA(
  id BIGINT IDENTITY NOT NULL,
  value nvarchar(max) NOT NULL
);

CREATE TABLE TableB(
  id BIGINT IDENTITY NOT NULL,
  value nvarchar(max) NOT NULL,
  tableARid BIGINT NOT NULL
)

INSERT INTO TableA(value) VALUES('test');
INSERT INTO TableB(value, tableARid) VALUES ('test1', 1);
INSERT INTO TableB(value, tableARid) VALUES ('test2', 1);
INSERT INTO TableB(value, tableARid) VALUES ('test3', 1);

我希望从中获取JSON,以便TableB值作为一个简单数组。因此,当我尝试这样查询时:

SELECT id,
       value,
       (SELECT value from TableB FOR JSON PATH) AS 'tableBValues'
FROM TableA
    FOR JSON PATH

结果将是

[
  {
    "id": 1,
    "value": "test",
    "tableBValues": [
      {
        "value": "test1"
      },
      {
        "value": "test2"
      },
      {
        "value": "test3"
      }
    ]
  }
]

是否可以使用JSON PATH查询,以便结果如下所示:

[
  {
    "id": 1,
    "value": "test",
    "tableBValues": [
      "test1",
      "test2",
      "test3"
    ]
  }
]

结果tableBValues数组中没有内部JSON对象吗?

0 个答案:

没有答案