I am doing an API call which returns the following JSON as a string:
[{
"id": 103000180455,
"name": "Personal",
"created_at": "2023-06-12T07:12:52Z",
"updated_at": "2023-06-12T07:12:52Z",
"personal": true,
"responses_count": 1
}, {
"id": 103000180454,
"name": "General",
"created_at": "2023-06-12T07:12:52Z",
"updated_at": "2023-06-12T07:12:52Z",
"personal": false,
"responses_count": 2
}, {
"id": 103000181609,
"name": "Custom",
"created_at": "2023-06-14T15:51:01Z",
"updated_at": "2023-06-14T15:51:01Z",
"personal": false,
"responses_count": 3
}]
What I want to do, is insert all of these into an already existing SQL Table.
My table consists of columns which already exist in the JSON.
eg.
ID
Name
Created_At etc. etc.
id | name | created_at | updated_at | personal | responses_count |
---|---|---|---|---|---|
103000180455 | Personal | 2023-06-12T07:12:52Z | 2023-06-12T07:12:52Z | true | 1 |
103000180454 | General | 2023-06-12T07:12:52Z | 2023-06-12T07:12:52Z | false | 2 |
103000181609 | Custom | 2023-06-12T07:12:52Z | 2023-06-12T07:12:52Z | false | 3 |
What I also want to do, is if the ID already exists, is to update the fields, rather than insert new ones. As the API call could bring back more objects if that makes sense?
Any help would be great, Cheers! 🙂
I have tried multiple tutorials online, but all of which create the table for you, or inserts the data manually. As I am having an automated process, this won’t work.
2
Answers
You can try this :
MERGE (Transact-SQL)
This documentation provides detailed explanations, examples, and syntax for using the
MERGE
statement to perform insert, update, or delete operations based on data from a source table or query. The provided example in my response demonstrates the usage ofMERGE
with JSON data.Use
OPENJSON
to convert JSON to a rowset :Result :
Demo here
This can then be used as source of a merge query .