SQL Server How to insert JSON to an existing table without specifying column names?

brc7rcf0  于 2023-02-18  发布在  其他
关注(0)|答案(2)|浏览(162)

To a table with two columns, named Id and Name , how can I insert the following json as rows, but without explicitly specifying the column names of the table (i.e. without WITH (Id ..., Name ... )?

[
    {
        "Id": "f08af9c2-8e67-4a7f-9413-1afffa2de96b",
        "SomeOtherKey": " ... ",
        "Name": "The One",
        ...
    },
    {
        "Name": "All is one"
        "Id": "9bbb094b-aa64-4c36-90a2-50e10f91c6a3",
        "Whatever": 99,
        ...
    },

    {       
        "Id": "af9d22d8-1e46-4d57-8179-75f094d2efa1",
        "SomeArrayWhyNot": [0, 1, 1, 2, 3, 5, 8, 13, 21]
        "Surprise": "This one does not have a Name value!!! 😱"
        ...
    },

    ...
]

The question is basically how to make SQL match the key-name to its suitable column name, ignoring json values with keys that do not have suitable column names, resulting with the following table (for the above json example):

IdName
f08af9c2-8e67-4a7f-9413-1afffa2de96bThe One
9bbb094b-aa64-4c36-90a2-50e10f91c6a3All is one
af9d22d8-1e46-4d57-8179-75f094d2efa1NULL
......
4dbbbstv

4dbbbstv1#

You can use the OPENJSON function in SQL Server to parse the JSON data and then use INSERT INTO to insert the data into the table.

INSERT INTO YourTable (Id, Name)
SELECT *
FROM OPENJSON('[
    {
        "Id": "f08af9c2-8e67-4a7f-9413-1afffa2de96b",
        "SomeOtherKey": " ... ",
        "Name": "The One"
    },
    {
        "Name": "All is one",
        "Id": "9bbb094b-aa64-4c36-90a2-50e10f91c6a3",
        "Whatever": 99
    },
    {       
        "Id": "af9d22d8-1e46-4d57-8179-75f094d2efa1",
        "SomeArrayWhyNot": [0, 1, 1, 2, 3, 5, 8, 13, 21],
        "Surprise": "This one doesn\'t have a Name value!!! 😱"
    }
]') WITH (Id nvarchar(50) '$.Id', Name nvarchar(50) '$.Name')
72qzrwbm

72qzrwbm2#

Not sure why you want this, but you can also do this:

INSERT INTO YourTable (Id, Name)
SELECT JSON_VALUE(x.value, '$.Id'), JSON_VALUE(x.value, '$.Name')
FROM OPENJSON('[{
        "Id": "f08af9c2-8e67-4a7f-9413-1afffa2de96b",
        "SomeOtherKey": " ... ",
        "Name": "The One"
    },
    {
        "Name": "All is one",
        "Id": "9bbb094b-aa64-4c36-90a2-50e10f91c6a3",
        "Whatever": 99
    },
    {       
        "Id": "af9d22d8-1e46-4d57-8179-75f094d2efa1",
        "SomeArrayWhyNot": [0, 1, 1, 2, 3, 5, 8, 13, 21],
        "Surprise": "This one doesn''t have a Name value!!! 😱"
    }]') x

相关问题