测试以查看嵌套JSON数组中是否存在值

时间:2017-12-28 19:29:17

标签: json sql-server sql-server-json

我有一个SQL 2016表,其中包含一个包含JSON数据的列。示例JSON文档如下所示:

{
    "_id": "5a450f0383cac0d725cd6735",
    "firstname": "Nanette",
    "lastname": "Mccormick",
    "registered": "2016-07-10T01:50:10 +04:00",
    "friends": [
      {
        "id": 0,
        "name": "Cote Collins",
        "interests": [
          "Movies",
          "Movies",
          "Cars"
        ]
      },
      {
        "id": 1,
        "name": "Ratliff Ellison",
        "interests": [
          "Birding",
          "Birding",
          "Chess"
        ]
      },
      {
        "id": 2,
        "name": "William Ratliff",
        "interests": [
          "Music",
          "Chess",
          "Software"
        ]
      }
    ],
    "greeting": "Hello, Nanette! You have 4 unread messages.",
    "favoriteFruit": "apple"
  }

我想提取所有文件,其中每个interests对象的friends数组包含特定值。我试过这个但没有结果:

Select *
From <MyTable>
Where 'Chess' IN (Select value From OPENJSON(JsonValue, '$.friends.interests'))

我应该已经返回了几行。我不能正确引用兴趣数组,也不能理解SQL Server如何处理这种类型的JSON数组。

1 个答案:

答案 0 :(得分:2)

由于Interests是嵌套数组,因此您需要解析数组级别。为此,您可以将CROSS APPLYOPENJSON()一起使用。第一个CROSS APPLY将获取朋友的名字和感兴趣的JSON数组,然后第二个CROSS APPLY将兴趣从数组中拉出来并用适当的朋友名称来确定它们。这是一个示例查询:

Select [name]
From #MyTable
CROSS APPLY OPENJSON(JsonValue, '$.friends')
WITH ([name] NVARCHAR(100) '$.name',
        interests NVARCHAR(MAX) AS JSON)
CROSS APPLY OPENJSON(interests)
WITH (Interest NVARCHAR(100) '$')
WHERE Interest = 'Chess'