次の 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