0

I am trying to both

  1. Save a JSON string to a table cell
  2. Parse part of the JSON string and set it to its own cell

Using SQL Server

 create procedure json_parse_and_update
   @i int,
   @json nvarchar(max)
 as 

update testTable
set 
json_str = @json, -- Save entire JSON string to table cell
json_prop1 = json_value(my_prop,'$.nested.property'), -- Parse JSON and update a single column 
json_prop2 = json_value(my_prop2,'$.nested2.property2')
from @json
where [key] = @i;

However, I'm not sure how to select a JSON property from a variable, the examples I see are selecting JSON properties from a table.

declare @json nvarchar(max) = '{
  "nested": {
    "property1": "value",
    "property2": 0
  },
  "nested2": {
    "property1": "value",
    "property2": 0
  }
}'

Test table is like

json_str | json_prop1       | json_prop_2       |
---------+------------------+-------------------+
json_str | nested_property1 | nested2_property2 |

How would I select and update nested.property into a column named json_prop1?

4
  • "I'm not sure how to select a JSON property from a variable" just replace the column's name with the variable's name. It's the same logic that you would use if yo7u wanted to return a variable in a SELECT statement instead of a column. SELECT @MyVarable, MyColumn;
    – Thom A
    Commented Jun 27, 2019 at 13:29
  • Like... json_prop = (select json_value(my_prop,'$.nested.property') from @json)?
    – Matthew
    Commented Jun 27, 2019 at 13:32
  • Is there going to be more than one property in your json? Show what testtable looks like.
    – dfundako
    Commented Jun 27, 2019 at 13:35
  • @dfundako Yes, more than one property. I have updated with an example table.
    – Matthew
    Commented Jun 27, 2019 at 13:40

1 Answer 1

1

What is my_prop? Try to do like this:

json_prop1 = json_value(@json,'$.nested.property')
json_prop2 = json_value(@json,'$.nested2.property2')
1
  • 1
    you don't need to casting a variable name, you can update the column json_prop1 directly with json_value like I did above. json_prop1 = json_value(@json,'$.nested.property') Commented Jun 27, 2019 at 13:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.