Как сохранить данные, полученные из вложенного json, в sql server

#sql #json #sql-server

Вопрос:

Я использую следующий код для получения данных из вложенного JSON.

  declare @json nvarchar(max)
set @json = '
[{

        "IdProject": "1",
        "Name": "Test Project",
        "SubSection": [{
            "IdStructure": "11",
            "IdProject": "1",
            "Name": "Test Structure",
            "Items": [{
                    "IdProperty": "111",
                    "IdStructure": "11",
                    "Name": "Test Property 2",
                    "DataType": 1,
                    "Precision": 0,
                    "Scale": 0,
                    "IsNullable": false,
                    "ObjectName": "Test Object",
                    "DefaultType": 1,
                    "DefaultValue": ""
                },
                {
                    "IdProperty": "112",
                    "IdStructure": "11",
                    "Name": "Test Property 1",
                    "DataType": 1,
                    "Precision": 0,
                    "Scale": 0,
                    "IsNullable": false,
                    "ObjectName": "Test Object",
                    "DefaultType": 1,
                    "DefaultValue": ""
                }
            ]
        }]
    },
    {
        "IdProject": "2",
        "Name": "Test Project",
        "SubSection": [{
            "IdStructure": "22",
            "IdProject": "2",
            "Name": "Test Structure",
            "Items": [{
                "IdProperty": "222",
                "IdStructure": "22",
                "Name": "Test Property 2",
                "DataType": 1,
                "Precision": 0,
                "Scale": 0,
                "IsNullable": false,
                "ObjectName": "Test Object",
                "DefaultType": 1,
                "DefaultValue": ""
            }]
        }]

    },
    {
        "IdProject": "3",
        "Name": "Test Project",
        "SubSection": [{}]

    },
    {
        "IdProject": "4",
        "Name": "Test Project",
        "SubSection": [{
            "IdStructure": "44",
            "IdProject": "4",
            "Name": "Test Structure"
        }]

    }
]';
select
    Projects.IdProject, Projects.Name as NameProject,
    Structures.IdStructure, Structures.Name as NameStructure,
    Properties.* 
from   openjson (@json) 
with
(
    IdProject int,
    Name nvarchar(100),
    SubSection nvarchar(max) as json
)
as Projects
outer apply openjson (Projects.SubSection)
with
(
    IdStructure int,
    Name nvarchar(100),
    Items nvarchar(max) as json
) as Structures
outer apply openjson (Structures.Items)
with
(
    IdProperty int,
    NamePreoperty nvarchar(100) '$.Name',
    DataType int,
    [Precision] int,
    [Scale] int,
    IsNullable bit,
    ObjectName nvarchar(100),
    DefaultType int,
    DefaultValue nvarchar(100)
)
as Properties
 

Я могу получать данные, и это работает нормально.

Проблема: Как я могу вставить данные в соответствующие таблицы. У меня есть три таблицы, которые находятся в отношениях:

  1. Проект
  2. подраздел
  3. Товары

Заранее спасибо

Комментарии:

1. Вы можете использовать команду вставить в проект, выбрать отдельный IdProject, NameProject из (выполняемого запроса) и то же самое с двумя другими таблицами.

2. Что не так с ан INSERT ?

3. Примечание сбоку: "SubSection": [{}] выглядит неправильно, это приведет к одной пустой строке. Это должно быть "SubSection": null или "SubSection": [ ]

Ответ №1:

Вам нужно сделать это как отдельные инструкции insert:

  declare @json nvarchar(max)
set @json = '
[{

        "IdProject": "1",
        "Name": "Test Project",
        "SubSection": [{
            "IdStructure": "11",
            "IdProject": "1",
            "Name": "Test Structure",
            "Items": [{
                    "IdProperty": "111",
                    "IdStructure": "11",
                    "Name": "Test Property 2",
                    "DataType": 1,
                    "Precision": 0,
                    "Scale": 0,
                    "IsNullable": false,
                    "ObjectName": "Test Object",
                    "DefaultType": 1,
                    "DefaultValue": ""
                },
                {
                    "IdProperty": "112",
                    "IdStructure": "11",
                    "Name": "Test Property 1",
                    "DataType": 1,
                    "Precision": 0,
                    "Scale": 0,
                    "IsNullable": false,
                    "ObjectName": "Test Object",
                    "DefaultType": 1,
                    "DefaultValue": ""
                }
            ]
        }]
    },
    {
        "IdProject": "2",
        "Name": "Test Project",
        "SubSection": [{
            "IdStructure": "22",
            "IdProject": "2",
            "Name": "Test Structure",
            "Items": [{
                "IdProperty": "222",
                "IdStructure": "22",
                "Name": "Test Property 2",
                "DataType": 1,
                "Precision": 0,
                "Scale": 0,
                "IsNullable": false,
                "ObjectName": "Test Object",
                "DefaultType": 1,
                "DefaultValue": ""
            }]
        }]

    },
    {
        "IdProject": "3",
        "Name": "Test Project",
        "SubSection": [{}]

    },
    {
        "IdProject": "4",
        "Name": "Test Project",
        "SubSection": [{
            "IdStructure": "44",
            "IdProject": "4",
            "Name": "Test Structure"
        }]

    }
]';
 
 insert Project
  (Id, Name)
select
    p.IdProject, p.Name
from   openjson (@json) 
with
(
    IdProject int,
    Name nvarchar(100)
) as p;

insert SubSection
  (Id, IdProject, Name)
select
    s.IdStructure, p.IdProject, s.Name
from   openjson (@json) 
with
(
    IdProject int,
    SubSection nvarchar(max) as json
) as p
cross apply openjson (p.SubSection)
with
(
    IdStructure int,
    Name nvarchar(100)
) as s;

insert Items
  (Id, IdStructure, NameProperty, DataType, [Precision], [Scale],
   IsNullable, ObjectName, DefaultType, DefaultValue)
select
   i.IdProperty, s.IdStructure, i.NameProperty, i.DataType, i.[Precision], i.[Scale],
   i.IsNullable, i.ObjectName, i.DefaultType, i.DefaultValue
from   openjson (@json) 
with
(
    SubSection nvarchar(max) as json
) as p
cross apply openjson (p.SubSection)
with
(
    IdStructure int,
    Items nvarchar(max) as json
) as s
cross apply openjson (s.Items)
with
(
    IdProperty int,
    NameProperty nvarchar(100) '$.Name',
    DataType int,
    [Precision] int,
    [Scale] int,
    IsNullable bit,
    ObjectName nvarchar(100),
    DefaultType int,
    DefaultValue nvarchar(100)
)
as i