3

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

鉴于此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'))

这是我应该做交叉申请的地方吗?

4

1 回答 1

6

这是我应该做交叉申请的地方吗?

是的。

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)
于 2017-07-31T23:24:38.813 回答