Skip to content
Advertisement

Update table using JSON in SQL

Is there a way to update a table using a JSON field in SQL.

Table structure

If I update the table using the above mentioned JSON file in SQL server the output should be changed as below by matching the FromID to ID.

In order to achieve this currently I am using the below query.

I am iterating the @Relationship table and updating the data. Is there a proper way to do it using JSON operations without iterating the temp table.

Advertisement

Answer

First, you need to specify the path '$.RelationshipType' in OPENJSON() to make it extract the data correctly.

Second, it is possible to JOIN OPENJSON() results just like any table, also using UPDATE, as follows:

See it in action:
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=c37ef5a175c0f19e0f990dc6a219ce26

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement