我正在尝试将嵌套的JSON连接到SQL中,该怎么做。
请帮助我解决这个问题。
示例:我的JSON如下所示。
[
{
"Name": "Cards",
"Value": [
"Pack of 24 Dare Cards"
],
"SourceSpecified": false,
"Any": []
},
{
"Name": "Boppers and Shot Glasses",
"Value": [
"12 Willy Shot Glass and 12 Hen Boppers"
],
"SourceSpecified": false,
"Any": []
}
]
我要输出:
Pack of 24 Dare Cards-12 Willy Shot Glass and 12 Hen Boppers
答案 0 :(得分:1)
如果Value始终包含一个元素
DECLARE @JSON NVARCHAR(MAX) = ' [
{
"Name": "Cards",
"Value": [
"Pack of 24 Dare Cards"
],
"SourceSpecified": false,
"Any": []
},
{
"Name": "Boppers and Shot Glasses",
"Value": [
"12 Willy Shot Glass and 12 Hen Boppers"
],
"SourceSpecified": false,
"Any": []
}
]'
SELECT STRING_AGG(Val, '-')
FROM OPENJSON(@JSON)
WITH (Val NVARCHAR(MAX) '$.Value[0]')
支持多个值也很容易。
SELECT STRING_AGG(Val, '-')
FROM OPENJSON(@JSON)
WITH (VALUE NVARCHAR(MAX) '$.Value' AS JSON)
OUTER APPLY OPENJSON(VALUE) WITH (Val NVARCHAR(MAX) '$')
答案 1 :(得分:0)
我通过创建一个标量值函数来填充级联值来实现这一目标。
Create FUNCTION [dbo].[test]
(
@VariationData nvarchar(max)
)
RETURNS nvarchar(max)
AS
BEGIN
Declare @val nvarchar(max)
select @val = COALESCE(@val+', ','')+ Value from OPENJSON(@VariationData)
With ([Value] NVARCHAR(MAX) N'$.Value[0]')
return @val
END
调用具有嵌套JSON值的函数,即
Select [dbo].[test] (@JSON);
这对我有用。