gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:44:34 25 4
gpt4 key购买 nike

是否可以在 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'))

这是我应该进行交叉应用的地方吗?

最佳答案

Is this where I should be doing a 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)

关于json - 使用Sql Server 2016的OPENJSON函数从Json文档中的多个数组元素中选择结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45426043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com