使用Sql Server 2016的OPENJSON函数从Json文档中的多个数组元素中选择结果

时间:2017-07-31 22:09:06

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

是否可以将来自多个数组元素的json文档的各个部分组合到Sql Server 2016中的单个结果中?

鉴于此json:

{
  "fruit": {
    "types": [
      {
        "possible": [ "Apples", "Bananas", "Pears" ],
        "category": "Basic"
      },
      {
        "possible": [ "Oranges", "Grapefruit", "Lemons", "Limes" ],
        "category": "Citrus"
      },
      {
        "possible": [ "Blueberries", "Strawberries", "Cherries" ],
        "category": "Berries"
      }
    ]
  }
}

我希望看到可能元素中所有值的单个结果:

results
-----
Apples
Bananas
Pears
Oranges
Grapefruit
Lemons
Limes
Blueberries
Strawberries
Cherries

我已经接近这样做了:

SELECT * FROM OPENJSON(JSON_QUERY(@json, '$.fruit.types[0].possible'))
UNION
SELECT * FROM OPENJSON(JSON_QUERY(@json, '$.fruit.types[1].possible'))
UNION
SELECT * FROM OPENJSON(JSON_QUERY(@json, '$.fruit.types[2].possible'))

但这依赖于将查询绑定到数组中的元素数量。 有没有办法在不必单独指定每个数组元素的情况下执行此操作?像这样的东西(这些都不是有效的表达式):

SELECT * FROM OPENJSON(JSON_QUERY(@json, '$.fruit.types[].possible'))

SELECT * FROM OPENJSON(JSON_QUERY(@json, '$.fruit.types.possible'))

这是我应该在做CROSS APPLY吗?

1 个答案:

答案 0 :(得分:3)

  

这是我应该在做CROSS APPLY吗?

是的。

declare @json nvarchar(max)='
{
  "fruit": {
    "types": [
      {
        "possible": [ "Apples", "Bananas", "Pears" ],
        "category": "Basic"
      },
      {
        "possible": [ "Oranges", "Grapefruit", "Lemons", "Limes" ],
        "category": "Citrus"
      },
      {
        "possible": [ "Blueberries", "Strawberries", "Cherries" ],
        "category": "Berries"
      }
    ]
  }
}
'

select v.value
from openjson(@json, '$.fruit.types') t
cross apply openjson(t.value,'$.possible') v

输出

value
---------
Apples
Bananas
Pears
Oranges
Grapefruit
Lemons
Limes
Blueberries
Strawberries
Cherries

(10 row(s) affected)