查询JSON数组元素?

时间:2016-06-23 20:20:27

标签: sql json sql-server-2016

是否可以对数组元素运行查询?似乎它在顶级项目上工作正常......让我说我有这个json:

{
  "_id": "5769cfbf7e45b52e388bbc78",
  "address": {
    "street": "2 Avenue",
    "zipcode": "10075",
    "building": "1480",
    "coord": [
      73.9557413,
      40.7720266
    ]
  },
  "borough": "Manhattan",
  "cuisine": "Italian",
  "grades": [
    {
      "date": "2014-10-01T00:00:00.000Z",
      "grade": "A",
      "score": 11
    },
    {
      "date": "2014-01-06T00:00:00.000Z",
      "grade": "B",
      "score": 17
    }
  ],
  "name": "Vella",
  "restaurant_id": "41704620"
}

是否可以使用JSON_QUERY / JSON_VALUE对成绩[xxx] .score执行where子句?即我想返回所有grade.score都是> = 17的文档。

1 个答案:

答案 0 :(得分:2)

SQL Azure和SQL Server 2016现在支持JSON。您可以在“EXISTS”子句中使用以下查询,或者需要的任何内容(假设@json包含给定的JSON数据):

SELECT g.score as score
FROM OPENJSON(@json) WITH (Id varchar(max)) j
    CROSS APPLY OPENJSON(JSON_QUERY(@json, '$.grades')) WITH (score int) AS g
WHERE g.score = 17