-2

数据库将具有链接到每个 SQL 级别的身份。还想将所有三个表的数据合并到一个主表 Table_master 中,该表将具有基于内部元素记录 id 2 的最终数据数。

预计使用外键将数据更新到 SQL Server 2016 表结构的表中以及如何将相同的数据再次导出到共享网络驱动器文件夹中的 Json 中。

表中将更新的预期数据

复制代码:

IF OBJECT_ID('dbo.Table1') IS NULL
    CREATE TABLE dbo.Table1
    (
    Name VARCHAR(100), Location VARCHAR(100), Region VARCHAR(100) 
    )


DECLARE @MYJSON VARCHAR(1000)

SET @MYJSON = '
{
  "Name":"ABC",
  "Location":"East US",
  "Region":"West US",
  "Element":
 [
     {  
        "Name":"IE1",
        "Description":"IE1 Description",
        "Type":"Small",
        "InnerElement":
        [ 
           { "Key":"Name", "Value":"IME1"},
           {"Key":"AnotherProperty","Value":"Value1"}
        ]
     },
     {  
        "Name":"IE2",
        "Description":"IE2 Description",
        "Type":"Medium",
        "InnerElement":
        [ 
           {"Key":"Name","Value":"IME2"},
           {"Key":"Address","Value":"Xyz"}, 
           {"Key":"Type","Value":"Simple"},
           {"Key":"LastProperty","Value":"ValueX"}
        ]
     }
 ]}
 '

SELECT 
JSON_VALUE(@MYJSON,'$.Name') As Name,
JSON_VALUE(@MYJSON,'$.Location') As Location,
JSON_VALUE(@MYJSON,'$.Region') As Region
4

1 回答 1

0
USE JSON_CAT GO DECLARE @JsonObject NVARCHAR(MAX) 
SELECT @JsonObject=BulkColumn from  openrowset  (BULK 'C:\Users\uverma\Desktop\Test.Json, SINGLE_CLOB)T 
BEGIN TRANSACTION;
INSERT Table1([Name], [Location], [Region])
SELECT [Name], [Location], [Region]
FROM OPENJSON(@JsonObject, '$.InnerElement')
WITH (    [Name] VARCHAR(100),    [Location] VARCHAR(100),    [Region] VARCHAR(100));
DECLARE @Table1Id INT = SCOPE_IDENTITY();
DECLARE @Table3Input TABLE([Table2Id] INT, [InnerMostElement] NVARCHAR(MAX));
MERGE Table2
USING (    SELECT [Name], [Description], [Type], [InnerMostElement]    
FROM OPENJSON(@JsonObject, '$.InnerElement')    
WITH (        [Name] VARCHAR(100),        [Description] VARCHAR(100),        [Type] VARCHAR(100),        [InnerMostElement] NVARCHAR(MAX) AS JSON    )) AS J 
ON 1 = 0    
-- Always INSERT
WHEN NOT MATCHED THEN     
INSERT([Table1Id], [Name], [Description], [Type])    
VALUES (@Table1Id, J.[Name], J.[Description], J.[Type])    
OUTPUT inserted.Id, J.[InnerMostElement]    
INTO @Table3Input([Table2Id], [InnerMostElement]);  

INSERT Table3([Table2Id], [Key], [Value]) 
SELECT [Table2Id], KV.[Key], KV.[Value] 
FROM @Table3Input 
CROSS APPLY (    SELECT [Key], [Value]    
FROM OPENJSON([InnerMostElement])    
WITH (        [Key] VARCHAR(100),[Value] VARCHAR(100))) AS KV;

COMMIT;

请看我已经尝试过了,我的数据也在导入,但是在数据库中插入的值变成了 null

于 2020-05-14T12:34:01.193 回答