I have a table with columns position_id
and column_id
. I am getting a JSON response from an API call, and I want to update my table using the value from the JSON response using the position_id
.
Here is an example
JSON Table:
Table in database(I am calling it #updateTable
):
I want to update my #updateTable
using the JSON input as below:
How can I achieve that? Is it possible without looping through table. Set based operation would be better I think.
(There are equal number of rows in JSON table and #updateTable
for a position_id
).
Here is the code for table creation that I have used in my example.
DROP TABLE IF EXISTS #inputJSONTable
DROP TABLE IF EXISTS #updateTable
DECLARE @inputJSON nvarchar(max) =
'[
{
"column_id":"7",
"position_id":"787",
"column1":"GoodValue",
"column2":"ReplacedValue"
},
{
"column_id":"8",
"position_id":"787",
"column1":"ReplacedValue",
"column2":"GoodValue"
}
]'
DECLARE @inJSON NVARCHAR(MAX);
SET @inJSON = RTRIM(LTRIM(@inputJSON));
SELECT
*
INTO
#inputJSONTable
FROM
OPENJSON(@inJSON)
WITH (
[column_id] VARCHAR(50) '$.column_id',
[position_id] VARCHAR(50) '$.position_id',
[column1] VARCHAR(50) '$.column1',
[column2] VARCHAR(50) '$.column2'
);
-- SELECT * FROM #inputJSONTable
CREATE TABLE #updateTable
(
Id INT IDENTITY(1, 1) PRIMARY KEY,
column_id INT,
position_id INT,
column1 VARCHAR(50),
column2 VARCHAR(50)
)
INSERT INTO #updateTable
VALUES (7, 787, 'GoodValue', 'ReplaceME'),
(8 , 787, 'ReplaceME', 'GoodValue')
SELECT * FROM #inputJSONTable
SELECT * FROM #updateTable
Thanks for helping out.
UPDATE:
I used this join to update the table :
UPDATE up
SET up.column1 = ip.column1,
up.column2 = ip.column2
FROM #updateTable up
INNER JOIN #inputJSONTable ip ON up.column_id = ip.column_id
This query worked.
UPDATE up
SET up.column1 = ip.column1,
up.column2 = ip.column2
FROM #updateTable up
INNER JOIN #inputJSONTable ip ON up.column_id = ip.column_id