Update table using JSON in SQL












2















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



{
"RelationshipType" : [
{
"ID" : 1,
"FromID" : 70,
"ToID" : 12
},
{
"ID" : 3,
"FromID" : 80,
"ToID" : 1
}
]
}


Table structure



ID    |    FromID    |    ToID    |
1 | 10 | 12 |
2 | 42 | 17 |
3 | 100 | 1 |


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.



ID    |    FromID    |    ToID    |
1 | 70 | 12 |
2 | 42 | 17 |
3 | 80 | 1 |


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



DECLARE @Relationship AS TABLE(FromID INT,ToID INT,ID INT)
INSERT INTO @Relationship (FromID,ToID,ID)
SELECT FromID, ToID, ID
FROM OPENJSON(@RelationshipType)
WITH (FromID INT, ToID INT, ID INT)


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.










share|improve this question

























  • Please see if this answer stackoverflow.com/a/51697340/1220550 helps you (also, that question might be a duplicate of this one).

    – Peter B
    Nov 19 '18 at 9:17











  • @PeterB, if I get this "I am iterating the @Relationship table" correctly, the point is not the reading of the JSON, but the udate in one go...

    – Shnugo
    Nov 19 '18 at 10:09













  • @Shnugo. Exactly, Is there a solution in order to update the table directly without feeding the data to a Temp Table or a CTE?

    – Harsha W
    Nov 19 '18 at 10:10













  • @HarshaW, just check my answer... You can use UPDATE with a JOIN, or - my prefered approach - an updatable CTE. At least for me this is better to read...

    – Shnugo
    Nov 19 '18 at 10:20











  • @Shnugo Sure, Ill try this and get back to you :-)

    – Harsha W
    Nov 19 '18 at 10:25
















2















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



{
"RelationshipType" : [
{
"ID" : 1,
"FromID" : 70,
"ToID" : 12
},
{
"ID" : 3,
"FromID" : 80,
"ToID" : 1
}
]
}


Table structure



ID    |    FromID    |    ToID    |
1 | 10 | 12 |
2 | 42 | 17 |
3 | 100 | 1 |


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.



ID    |    FromID    |    ToID    |
1 | 70 | 12 |
2 | 42 | 17 |
3 | 80 | 1 |


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



DECLARE @Relationship AS TABLE(FromID INT,ToID INT,ID INT)
INSERT INTO @Relationship (FromID,ToID,ID)
SELECT FromID, ToID, ID
FROM OPENJSON(@RelationshipType)
WITH (FromID INT, ToID INT, ID INT)


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.










share|improve this question

























  • Please see if this answer stackoverflow.com/a/51697340/1220550 helps you (also, that question might be a duplicate of this one).

    – Peter B
    Nov 19 '18 at 9:17











  • @PeterB, if I get this "I am iterating the @Relationship table" correctly, the point is not the reading of the JSON, but the udate in one go...

    – Shnugo
    Nov 19 '18 at 10:09













  • @Shnugo. Exactly, Is there a solution in order to update the table directly without feeding the data to a Temp Table or a CTE?

    – Harsha W
    Nov 19 '18 at 10:10













  • @HarshaW, just check my answer... You can use UPDATE with a JOIN, or - my prefered approach - an updatable CTE. At least for me this is better to read...

    – Shnugo
    Nov 19 '18 at 10:20











  • @Shnugo Sure, Ill try this and get back to you :-)

    – Harsha W
    Nov 19 '18 at 10:25














2












2








2








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



{
"RelationshipType" : [
{
"ID" : 1,
"FromID" : 70,
"ToID" : 12
},
{
"ID" : 3,
"FromID" : 80,
"ToID" : 1
}
]
}


Table structure



ID    |    FromID    |    ToID    |
1 | 10 | 12 |
2 | 42 | 17 |
3 | 100 | 1 |


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.



ID    |    FromID    |    ToID    |
1 | 70 | 12 |
2 | 42 | 17 |
3 | 80 | 1 |


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



DECLARE @Relationship AS TABLE(FromID INT,ToID INT,ID INT)
INSERT INTO @Relationship (FromID,ToID,ID)
SELECT FromID, ToID, ID
FROM OPENJSON(@RelationshipType)
WITH (FromID INT, ToID INT, ID INT)


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.










share|improve this question
















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



{
"RelationshipType" : [
{
"ID" : 1,
"FromID" : 70,
"ToID" : 12
},
{
"ID" : 3,
"FromID" : 80,
"ToID" : 1
}
]
}


Table structure



ID    |    FromID    |    ToID    |
1 | 10 | 12 |
2 | 42 | 17 |
3 | 100 | 1 |


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.



ID    |    FromID    |    ToID    |
1 | 70 | 12 |
2 | 42 | 17 |
3 | 80 | 1 |


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



DECLARE @Relationship AS TABLE(FromID INT,ToID INT,ID INT)
INSERT INTO @Relationship (FromID,ToID,ID)
SELECT FromID, ToID, ID
FROM OPENJSON(@RelationshipType)
WITH (FromID INT, ToID INT, ID INT)


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.







sql json sql-server tsql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 '18 at 9:11









JohnLBevan

14.4k146107




14.4k146107










asked Nov 19 '18 at 8:32









Harsha WHarsha W

95211532




95211532













  • Please see if this answer stackoverflow.com/a/51697340/1220550 helps you (also, that question might be a duplicate of this one).

    – Peter B
    Nov 19 '18 at 9:17











  • @PeterB, if I get this "I am iterating the @Relationship table" correctly, the point is not the reading of the JSON, but the udate in one go...

    – Shnugo
    Nov 19 '18 at 10:09













  • @Shnugo. Exactly, Is there a solution in order to update the table directly without feeding the data to a Temp Table or a CTE?

    – Harsha W
    Nov 19 '18 at 10:10













  • @HarshaW, just check my answer... You can use UPDATE with a JOIN, or - my prefered approach - an updatable CTE. At least for me this is better to read...

    – Shnugo
    Nov 19 '18 at 10:20











  • @Shnugo Sure, Ill try this and get back to you :-)

    – Harsha W
    Nov 19 '18 at 10:25



















  • Please see if this answer stackoverflow.com/a/51697340/1220550 helps you (also, that question might be a duplicate of this one).

    – Peter B
    Nov 19 '18 at 9:17











  • @PeterB, if I get this "I am iterating the @Relationship table" correctly, the point is not the reading of the JSON, but the udate in one go...

    – Shnugo
    Nov 19 '18 at 10:09













  • @Shnugo. Exactly, Is there a solution in order to update the table directly without feeding the data to a Temp Table or a CTE?

    – Harsha W
    Nov 19 '18 at 10:10













  • @HarshaW, just check my answer... You can use UPDATE with a JOIN, or - my prefered approach - an updatable CTE. At least for me this is better to read...

    – Shnugo
    Nov 19 '18 at 10:20











  • @Shnugo Sure, Ill try this and get back to you :-)

    – Harsha W
    Nov 19 '18 at 10:25

















Please see if this answer stackoverflow.com/a/51697340/1220550 helps you (also, that question might be a duplicate of this one).

– Peter B
Nov 19 '18 at 9:17





Please see if this answer stackoverflow.com/a/51697340/1220550 helps you (also, that question might be a duplicate of this one).

– Peter B
Nov 19 '18 at 9:17













@PeterB, if I get this "I am iterating the @Relationship table" correctly, the point is not the reading of the JSON, but the udate in one go...

– Shnugo
Nov 19 '18 at 10:09







@PeterB, if I get this "I am iterating the @Relationship table" correctly, the point is not the reading of the JSON, but the udate in one go...

– Shnugo
Nov 19 '18 at 10:09















@Shnugo. Exactly, Is there a solution in order to update the table directly without feeding the data to a Temp Table or a CTE?

– Harsha W
Nov 19 '18 at 10:10







@Shnugo. Exactly, Is there a solution in order to update the table directly without feeding the data to a Temp Table or a CTE?

– Harsha W
Nov 19 '18 at 10:10















@HarshaW, just check my answer... You can use UPDATE with a JOIN, or - my prefered approach - an updatable CTE. At least for me this is better to read...

– Shnugo
Nov 19 '18 at 10:20





@HarshaW, just check my answer... You can use UPDATE with a JOIN, or - my prefered approach - an updatable CTE. At least for me this is better to read...

– Shnugo
Nov 19 '18 at 10:20













@Shnugo Sure, Ill try this and get back to you :-)

– Harsha W
Nov 19 '18 at 10:25





@Shnugo Sure, Ill try this and get back to you :-)

– Harsha W
Nov 19 '18 at 10:25












2 Answers
2






active

oldest

votes


















1














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:



UPDATE U
SET FromID = J.FromID
FROM YourTable AS U
JOIN OPENJSON(@RelationshipType, '$.RelationshipType')
WITH (ID INT, FromID INT, ToID INT) J
ON J.ID = U.ID


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






share|improve this answer


























  • Thanks @PeterB, This is what I was looking for

    – Harsha W
    Nov 19 '18 at 11:20



















1














Your OPENJSON is missing the path... Isn't it?



DECLARE @relationshipType NVARCHAR(MAX)=
N'{
"RelationshipType" : [
{
"ID" : 1,
"FromID" : 70,
"ToID" : 12
},
{
"ID" : 3,
"FromID" : 80,
"ToID" : 1
}
]
}';


--This is to mock-up your existing data



DECLARE @ExistingTable AS TABLE(ID INT,FromID INT,ToID INT)
INSERT INTO @ExistingTable VALUES(1,10,12),(2,42,17),(3,100,1);


--The query will use two CTEs:

--1) Get the JSON data as list

--2) Bind the new data to the corresponding rows



WITH newData AS
(
SELECT *
FROM OPENJSON(@relationshipType,'$.RelationshipType')
WITH (FromID INT, ToID INT, ID INT)
)
,updatableCTE AS
(
SELECT et.*
,nd.FromID AS newFromID
,nd.ToID AS newToID
FROM @ExistingTable et
INNER JOIN newData nd ON et.ID=nd.ID
)
UPDATE updatableCTE SET FromID=newFromID
,ToID=newToID;


--check the result



SELECT ID,FromID,ToID FROM @ExistingTable;


The result



ID  FromID    ToID
1 70 12
2 42 17
3 80 1





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53370886%2fupdate-table-using-json-in-sql%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    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:



    UPDATE U
    SET FromID = J.FromID
    FROM YourTable AS U
    JOIN OPENJSON(@RelationshipType, '$.RelationshipType')
    WITH (ID INT, FromID INT, ToID INT) J
    ON J.ID = U.ID


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






    share|improve this answer


























    • Thanks @PeterB, This is what I was looking for

      – Harsha W
      Nov 19 '18 at 11:20
















    1














    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:



    UPDATE U
    SET FromID = J.FromID
    FROM YourTable AS U
    JOIN OPENJSON(@RelationshipType, '$.RelationshipType')
    WITH (ID INT, FromID INT, ToID INT) J
    ON J.ID = U.ID


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






    share|improve this answer


























    • Thanks @PeterB, This is what I was looking for

      – Harsha W
      Nov 19 '18 at 11:20














    1












    1








    1







    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:



    UPDATE U
    SET FromID = J.FromID
    FROM YourTable AS U
    JOIN OPENJSON(@RelationshipType, '$.RelationshipType')
    WITH (ID INT, FromID INT, ToID INT) J
    ON J.ID = U.ID


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






    share|improve this 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:



    UPDATE U
    SET FromID = J.FromID
    FROM YourTable AS U
    JOIN OPENJSON(@RelationshipType, '$.RelationshipType')
    WITH (ID INT, FromID INT, ToID INT) J
    ON J.ID = U.ID


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







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 19 '18 at 11:01

























    answered Nov 19 '18 at 10:46









    Peter BPeter B

    13.2k51943




    13.2k51943













    • Thanks @PeterB, This is what I was looking for

      – Harsha W
      Nov 19 '18 at 11:20



















    • Thanks @PeterB, This is what I was looking for

      – Harsha W
      Nov 19 '18 at 11:20

















    Thanks @PeterB, This is what I was looking for

    – Harsha W
    Nov 19 '18 at 11:20





    Thanks @PeterB, This is what I was looking for

    – Harsha W
    Nov 19 '18 at 11:20













    1














    Your OPENJSON is missing the path... Isn't it?



    DECLARE @relationshipType NVARCHAR(MAX)=
    N'{
    "RelationshipType" : [
    {
    "ID" : 1,
    "FromID" : 70,
    "ToID" : 12
    },
    {
    "ID" : 3,
    "FromID" : 80,
    "ToID" : 1
    }
    ]
    }';


    --This is to mock-up your existing data



    DECLARE @ExistingTable AS TABLE(ID INT,FromID INT,ToID INT)
    INSERT INTO @ExistingTable VALUES(1,10,12),(2,42,17),(3,100,1);


    --The query will use two CTEs:

    --1) Get the JSON data as list

    --2) Bind the new data to the corresponding rows



    WITH newData AS
    (
    SELECT *
    FROM OPENJSON(@relationshipType,'$.RelationshipType')
    WITH (FromID INT, ToID INT, ID INT)
    )
    ,updatableCTE AS
    (
    SELECT et.*
    ,nd.FromID AS newFromID
    ,nd.ToID AS newToID
    FROM @ExistingTable et
    INNER JOIN newData nd ON et.ID=nd.ID
    )
    UPDATE updatableCTE SET FromID=newFromID
    ,ToID=newToID;


    --check the result



    SELECT ID,FromID,ToID FROM @ExistingTable;


    The result



    ID  FromID    ToID
    1 70 12
    2 42 17
    3 80 1





    share|improve this answer




























      1














      Your OPENJSON is missing the path... Isn't it?



      DECLARE @relationshipType NVARCHAR(MAX)=
      N'{
      "RelationshipType" : [
      {
      "ID" : 1,
      "FromID" : 70,
      "ToID" : 12
      },
      {
      "ID" : 3,
      "FromID" : 80,
      "ToID" : 1
      }
      ]
      }';


      --This is to mock-up your existing data



      DECLARE @ExistingTable AS TABLE(ID INT,FromID INT,ToID INT)
      INSERT INTO @ExistingTable VALUES(1,10,12),(2,42,17),(3,100,1);


      --The query will use two CTEs:

      --1) Get the JSON data as list

      --2) Bind the new data to the corresponding rows



      WITH newData AS
      (
      SELECT *
      FROM OPENJSON(@relationshipType,'$.RelationshipType')
      WITH (FromID INT, ToID INT, ID INT)
      )
      ,updatableCTE AS
      (
      SELECT et.*
      ,nd.FromID AS newFromID
      ,nd.ToID AS newToID
      FROM @ExistingTable et
      INNER JOIN newData nd ON et.ID=nd.ID
      )
      UPDATE updatableCTE SET FromID=newFromID
      ,ToID=newToID;


      --check the result



      SELECT ID,FromID,ToID FROM @ExistingTable;


      The result



      ID  FromID    ToID
      1 70 12
      2 42 17
      3 80 1





      share|improve this answer


























        1












        1








        1







        Your OPENJSON is missing the path... Isn't it?



        DECLARE @relationshipType NVARCHAR(MAX)=
        N'{
        "RelationshipType" : [
        {
        "ID" : 1,
        "FromID" : 70,
        "ToID" : 12
        },
        {
        "ID" : 3,
        "FromID" : 80,
        "ToID" : 1
        }
        ]
        }';


        --This is to mock-up your existing data



        DECLARE @ExistingTable AS TABLE(ID INT,FromID INT,ToID INT)
        INSERT INTO @ExistingTable VALUES(1,10,12),(2,42,17),(3,100,1);


        --The query will use two CTEs:

        --1) Get the JSON data as list

        --2) Bind the new data to the corresponding rows



        WITH newData AS
        (
        SELECT *
        FROM OPENJSON(@relationshipType,'$.RelationshipType')
        WITH (FromID INT, ToID INT, ID INT)
        )
        ,updatableCTE AS
        (
        SELECT et.*
        ,nd.FromID AS newFromID
        ,nd.ToID AS newToID
        FROM @ExistingTable et
        INNER JOIN newData nd ON et.ID=nd.ID
        )
        UPDATE updatableCTE SET FromID=newFromID
        ,ToID=newToID;


        --check the result



        SELECT ID,FromID,ToID FROM @ExistingTable;


        The result



        ID  FromID    ToID
        1 70 12
        2 42 17
        3 80 1





        share|improve this answer













        Your OPENJSON is missing the path... Isn't it?



        DECLARE @relationshipType NVARCHAR(MAX)=
        N'{
        "RelationshipType" : [
        {
        "ID" : 1,
        "FromID" : 70,
        "ToID" : 12
        },
        {
        "ID" : 3,
        "FromID" : 80,
        "ToID" : 1
        }
        ]
        }';


        --This is to mock-up your existing data



        DECLARE @ExistingTable AS TABLE(ID INT,FromID INT,ToID INT)
        INSERT INTO @ExistingTable VALUES(1,10,12),(2,42,17),(3,100,1);


        --The query will use two CTEs:

        --1) Get the JSON data as list

        --2) Bind the new data to the corresponding rows



        WITH newData AS
        (
        SELECT *
        FROM OPENJSON(@relationshipType,'$.RelationshipType')
        WITH (FromID INT, ToID INT, ID INT)
        )
        ,updatableCTE AS
        (
        SELECT et.*
        ,nd.FromID AS newFromID
        ,nd.ToID AS newToID
        FROM @ExistingTable et
        INNER JOIN newData nd ON et.ID=nd.ID
        )
        UPDATE updatableCTE SET FromID=newFromID
        ,ToID=newToID;


        --check the result



        SELECT ID,FromID,ToID FROM @ExistingTable;


        The result



        ID  FromID    ToID
        1 70 12
        2 42 17
        3 80 1






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 19 '18 at 10:08









        ShnugoShnugo

        49.5k72668




        49.5k72668






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53370886%2fupdate-table-using-json-in-sql%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Academy of Television Arts & Sciences

            L'Équipe

            1995 France bombings