0

I have to parse a json like this:

[
    { "id": 2, "name": "John", "age": 25 },
    { "id": 5, "name": "Jane", "age": 18 }
]

I have to parse it and check if the name already exists in userInfo table. If the name is found in that table, then I only update the age.

Else, I have to insert the data into the userInfo table.

Here's what I did so far:

DROP TABLE IF EXISTS #tmp

DECLARE @json NVARCHAR(MAX);

SET @json = N'[
  {"id": 2, "name": "John", "age":25},
  {"id": 5, "name": "Jane", "age": 18} 
]';

SELECT [id], [info] 
INTO #tmp
FROM OPENJSON(@json)
WITH
    ([id] NVARCHAR(100), 
     [name] NVARCHAR(100),
     [age] Int);

SELECT * FROM #tmp

Now I want to insert or update these data in table userInfo.

If the name from #tmp table already exists in userInfo table, then update the age, else insert the data into the userInfo table.

I don't know what the syntax for this operation is, or if it is possible to do.

2
  • Why not do this logic this in your code Commented Mar 12, 2020 at 7:40
  • @hoangnh cause I've to do this inside stored procedure Commented Mar 12, 2020 at 7:43

1 Answer 1

2

You can use MERGE keyword for this

MERGE userInfo t 
    USING #tmp s
ON (s.name = t.name)
WHEN MATCHED
    THEN UPDATE SET 
        t.age = s.age
WHEN NOT MATCHED THEN 
         INSERT (name, age)
         VALUES (s.name, s.age);

Just to be more succinct I'd do the same this way

MERGE userInfo t 
        USING (SELECT *
FROM OPENJSON(@json)
WITH
(
[id] NVARCHAR(100), 
[name] NVARCHAR(100),
[age] Int
)) s
    ON (s.name = t.name)
    WHEN MATCHED
        THEN UPDATE SET 
            t.age = s.age
    WHEN NOT MATCHED THEN 
             INSERT (name, age)
             VALUES (s.name, s.age);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.