跨多个表解析和存储父/子JSON

时间:2018-11-08 17:03:40

标签: json sql-server sql-server-2016

此链接json part 3 open json显示了如何将json切成父子记录。

具体显示如何从一个Json Document生成多个结果集

[
    {
      "CharacterID" : null,
      "CharacterName" : "Egwene Al''Vere",
      "IsFemale" : true,
      "Address" : {
        "AddressLine1" : "Emonds Field",
        "AddressLine2" : "The Two Rivers"
      },
      "Friends" : ["Rand Al''Thor", "Perrin Aybara", "Matrim Cauthon"],
      "Children" : null
    },
    {
      "CharacterID" : null,
      "CharacterName" : "Second Character",
      "IsFemale" : false,
      "Address" : {
        "AddressLine1" : "Emonds Field 2",
        "AddressLine2" : "The Three Rivers"
      },
      "Friends" : ["Jeff", "Zeke", "Sid Cauthon"],
      "Children" : null
    }
]   

SELECT
 JSON_VALUE(@json, '$.CharacterID') AS CharacterID,
 JSON_VALUE(@json, '$.CharacterName') AS CharacterName,
 JSON_VALUE(@json, '$.IsFemale') AS IsFemale,
 JSON_VALUE(@json, '$.Address.AddressLine1') AS AddressLine1,
 JSON_VALUE(@json, '$.Address.AddressLine2') AS AddressLine2,
 JSON_VALUE(@json, '$.Children') AS Children

SELECT
  JSON_VALUE(@json, '$.CharacterID') AS CharacterID,
  OJ.value AS Friend
FROM OPENJSON(@json, '$.Friends') OJ;

我想编写一个程序来将此文档插入父性格表和子性格表中,以保持FK引用。

如果未提供ID,则很容易使用SCOPE IDENTITY找出其含义,然后在插入CharacterFriend表之前对其进行填写。

但是,对我而言,如果在json文档中定义了多个字符,那么我将如何发现Character表的PK尚不清楚。

在这种情况下,编写建立此FK的插入过程的最佳方法是什么。唯一让我跳出来的是光标,但这感觉不对。

0 个答案:

没有答案