使用 T-SQL 将 JSON 转换为表

Aey*_*Jey 2 t-sql sql-server json

这是 JSON 输入

{
   "agentID":"WJ",
   "recordType":"AHL",
   "recordReference":{
      "stationCode":"ATL",
      "airlineCode":"XS",
      "recordId":"10001"
   },
   "entries":[
      {
         "bag":{
            "bagType":"22",
            "bagSize":"S",
            "category":"1"
         },
         "seqNo":"1",
         "noOfBagsGiven":"2"
      },
      {
         "bag":{
            "bagType":"23",
            "bagSize":"L",
            "category":"1"
         },
         "seqNo":"2",
         "noOfBagsGiven":"5",
         "dateBagsGiven":"2019-09-18"
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

这是我希望得到的输出(表格或去限制) 在此输入图像描述

我不知道如何循环子条目,这是我到目前为止所拥有的

DECLARE @JSON    VARCHAR(MAX) =
'{
   "agentID":"WJ",
   "recordType":"AHL",
   "recordReference":{
      "stationCode":"ATL",
      "airlineCode":"XS",
      "recordId":"10001"
   },
   "entries":[
      {
         "bag":{
            "bagType":"22",
            "bagSize":"S",
            "category":"1"
         },
         "seqNo":"1",
         "noOfBagsGiven":"2"
      },
      {
         "bag":{
            "bagType":"23",
            "bagSize":"L",
            "category":"1"
         },
         "seqNo":"2",
         "noOfBagsGiven":"5",
         "dateBagsGiven":"2019-09-18"
      }
   ]
}';

SELECT *
FROM   OPENJSON(@json) WITH(agent_id        VARCHAR(2)  '$.agentID'
                           ,record_type     VARCHAR(4)  '$.recordType'
                           ,station_code    VARCHAR(4)  '$.recordReference.stationCode'
                           ,airline_code    VARCHAR(4)  '$.recordReference.airlineCode'
                           ,record_id       INT         '$.recordReference.recordId'
                           ,bag_type        INT         '$.entries.bag.bagType'
                           ,bag_size        VARCHAR(2)  '$.entries.bag.bagSize'
                           ,bag_category    INT         '$.entries.bag.bagCategory'
                           ,date_bags_given DATE        '$.entries.bag.dateBagsGiven'
                           );
Run Code Online (Sandbox Code Playgroud)

Zho*_*rov 6

另一种可能的方法是使用JSON_VALUE()(从字符串中提取标量值JSON)和OPENJSON()(解析JSON字符串并以表形式获取结果):

SELECT 
   JSON_VALUE(@JSON,'$.agentID') AS agentID,
   JSON_VALUE(@JSON,'$.recordType') AS recordType,
   JSON_VALUE(@JSON,'$.recordReference.stationCode') AS stationCode,
   JSON_VALUE(@JSON,'$.recordReference.airlineCode') AS airlineCode,
   JSON_VALUE(@JSON,'$.recordReference.recordId') AS recordId,
   j.*
FROM OPENJSON(@JSON, '$.entries') WITH (
   bagType VARCHAR(10) '$.bag.bagType',
   bagSize VARCHAR(10) '$.bag.bagSize',
   category VARCHAR(10) '$.bag.category',
   seqNo VARCHAR(10) '$.seqNo',
   noOfBagsGiven VARCHAR(10) '$.noOfBagsGiven',
   dateBagsGiven VARCHAR(10) '$.dateBagsGiven'
) AS j
Run Code Online (Sandbox Code Playgroud)