我是sqlserver的新手。我想将json数据转换为记录并插入表中。 我有json数据
{
"HEADER":[
{
"seq_id":343,
"max_processed_scn":649044274,
"time_processed":"13-MAR-19 09.03.23.081055 PM",
"status":"COMPLETED"
},
{
"seq_id":344,
"max_processed_scn":649214903,
"time_processed":"15-MAR-19 12.49.31.606172 PM",
"status":"COMPLETED"
}
],
"DETAIL":[
{
"seq_id":11215,
"event_id":1,
"caller_seq":343,
"event_description":"BEGIN.."
},
{
"seq_id":11216,
"event_id":2,
"caller_seq":343,
"event_description":"STARTING"
},
{
"seq_id":11217,
"event_id":2,
"caller_seq":343,
"event_description":"STARTED "
} "event_description":"TOTAL"
]
}
所以我想将数组“ header”插入一个表,将另一个数组“ Detail”插入另一个表。有人可以帮助我实现这一点。预先感谢
所以我需要像这样的明细表数据
seq_id max_processed_scn time_processed status
343 649044274 13-MAR-19 09.03.23.081055 PM COMPLETED
344 649214903 15-MAR-19 12.49.31.606172 PM COMPLETED
我使用了这个查询:
DECLARE @json NVARCHAR(MAX)
SET @json =
N'[{
"HEADER":[
{
"seq_id":343,
"max_processed_scn":649044274,
"time_processed":"13-MAR-19 09.03.23.081055 PM",
"status":"COMPLETED"
},
{
"seq_id":344,
"max_processed_scn":649214903,
"time_processed":"15-MAR-19 12.49.31.606172 PM",
"status":"COMPLETED"
}
],
"DETAIL":[
{
"seq_id":11215,
"event_id":1,
"caller_seq":343,
"event_description":"BEGIN.."
},
{
"seq_id":11216,
"event_id":2,
"caller_seq":343,
"event_description":"STARTING"
},
{
"seq_id":11217,
"event_id":2,
"caller_seq":343,
"event_description":"STARTED "
} "event_description":"TOTAL"
]
}
]'
SELECT *
FROM OPENJSON(@json, '$.HEADER')
WITH (seq_id INT, max_processed_scn INT, time_processed NVARCHAR(100), [status] NVARCHAR(100))
答案 0 :(得分:1)
您可以在sql server 2016及更高版本中使用以下查询来读取Json数据并插入所需的表中
样本数据
declare @json varchar(max) =' {
"HEADER":[
{
"seq_id":343,
"max_processed_scn":649044274,
"time_processed":"13-MAR-19 09.03.23.081055 PM",
"status":"COMPLETED"
},
{
"seq_id":344,
"max_processed_scn":649214903,
"time_processed":"15-MAR-19 12.49.31.606172 PM",
"status":"COMPLETED"
}
],
"DETAIL":[
{
"seq_id":11215,
"event_id":1,
"caller_seq":343,
"event_description":"BEGIN.."
},
{
"seq_id":11216,
"event_id":2,
"caller_seq":343,
"event_description":"STARTING"
},
{
"seq_id":11217,
"event_id":2,
"caller_seq":343,
"event_description":"STARTED "
}
]
}
'
查询以选择标题数据
SELECT * FROM OPENJSON(@json, '$.HEADER') WITH (seq_id INT, max_processed_scn INT, time_processed NVARCHAR(50), [status] NVARCHAR(50))
查询以选择详细数据
SELECT * FROM OPENJSON(@json, '$.DETAIL') WITH (seq_id INT, event_id INT, caller_seq int, event_description NVARCHAR(255))