考虑这个 JSON:
{
"Name": "Alice",
"Relations": [
{
"RelationId": 1,
"Value": "one"
},
{
"RelationId": 2,
"Value": "two"
}
]
}
我将此 JSON 传递给一个存储过程,在该存储过程中对其进行解析并插入名称:
-- parse JSON
WITH [source]
AS (SELECT *
FROM
OPENJSON(@json)
WITH
(
[Name] VARCHAR(50),
[Relations] VARCHAR(MAX)
) -- end json WITH
) -- end WITH [source] AS
-- insert Name
INSERT INTO dbo.names
(
[Name]
)
SELECT [s].[Name]
FROM [source] s;
接下来,我想插入关系,所以首先我OPENJSON
必须[Relations]
:
WITH [relationsSource]
AS (SELECT *
FROM
-- now, here is the problem: the CTE (common table expression)
-- named [source] isn't available anymore
OPENJSON(<how to access [source].[Relations] here?)
WITH
(
[RelationId] INT,
[Value] VARCHAR(50)
) -- end json WITH
) -- end WITH [relationsSource]
我知道我可以做类似的事情OPENJSON(@json, '$Relations')
。但这将@json
再次解析整个以搜索$Relations
路径,而不是仅解析先前提取的[source].[Relations]
.
有什么解决方案可以让我使用类似的东西
OPENJSON([source].[Relations]) -- pass only the Relations subset of @json
这样OPENJSON
就不必@json
再次解析完整了吗?