Search code examples
sqlsql-serversql-server-2016sql-server-json

SQL Server : update table with join condition using JSON input


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:

enter image description here

Table in database(I am calling it #updateTable):

enter image description here

I want to update my #updateTable using the JSON input as below:

enter image description here

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

Solution

  • 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