I have following Json Object in Sql server. I want to insert this data into multiple tables with their relation (i.e. foreign key):
DECLARE @JsonObject NVARCHAR(MAX) = N'{
"FirstElement":{
"Name":"ABC",
"Location":"East US",
"Region":"West US",
"InnerElement":[
{
"Name":"IE1",
"Description":"IE1 Description",
"Type":"Small",
"InnerMostElement":[
{
"Key":"Name",
"Value":"IME1"
},
{
"Key":"AnotherProperty",
"Value":"Value1"
}
]
},
{
"Name":"IE2",
"Description":"IE2 Description",
"Type":"Medium",
"InnerMostElement":[
{
"Key":"Name",
"Value":"IME2"
},
{
"Key":"Address",
"Value":"Xyz"
},
{
"Key":"Type",
"Value":"Simple"
},
{
"Key":"LastProperty",
"Value":"ValueX"
}
]
}
]
}
}'
The table structure is attached here:
I want to insert the FirstElement data in Table1, InnerElement data in Table2 and InnerMostElement data in Table3.
The easy part is the first table, because we're only inserting one row and it has no dependencies:
The hard part is the next table. We need to capture all the identities of the inserted rows, but also all the data yet to be inserted into table 3. Because the
OUTPUT
clause ofINSERT
is restricted to outputting values in the base table only, we need to useMERGE
trickery:If the tables are to be primarily filled using JSON, it may be more convenient to use
SEQUENCE
objects to generate consecutive values (usingsp_sequence_get_range
) without the need to capture the whole JSON into a temporary table. That would greatly simplify this and remove the need forMERGE
.The last table is easy again:
The transaction is logically necessary to ensure this object is entirely inserted, or not at all.
Final output:
For completeness, here's how you'd turn that back into JSON: