I have a SQL table Templates
, which has a column JsonContent
. I would like to modify the content of JsonContent
with SQL.
Each JsonContent
has serialized JSON array of objects. For example:
[
{
"Name":"Test name",
"Options":[
{
"Name":"1",
"Value":1
},
{
"Name":"2",
"Value":2
},
{
"Name":"3",
"Value":3
}
]
},
{
"Name":"Another name",
"Options":null
}
]
I would like to add new property to each object in Options
, which will be named IsDeleted
and set the value to false
. For example:
[
{
"Name":"Test name",
"Options":[
{
"Name":"1",
"Value":1,
"IsDeleted": false
},
{
"Name":"2",
"Value":2,
"IsDeleted": false
},
{
"Name":"3",
"Value":3,
"IsDeleted": false
}
]
},
{
"Name":"Another name",
"Options":null
}
]
How can I modify the first example with SQL and get the second example as a result?
2
Answers
Using the example from How to update insert JSON property in an array of object with T-SQL I applied your scenario:
One possible approach in this situation (but only if the stored JSON has a fixed structure) are the following steps:
OPENJSON()
calls with the appropriate explicit schemas.FOR JSON
.T-SQL: