1. jsonを解析する
適用対象: SQL Server 2016 (13.x)以降 Azure SQL Database Azure SQL Managed Instance Azure Synapse Analytics Microsoft Fabric の SQL エンドポイント Microsoft Fabric のウェアハウス
(1)OPENJSON()関数を使用する
declare @json as varchar(8000)
set @json='[
{"id":1178,"myObject.Plies":3,"myObject.Createtime":"2020-07-21T14:33:18.480"},
{"id":1179,"myObject.Plies":3,"myObject.Createtime":"2020-07-21T14:36:27.457"}]'
select * from openjson(@json);
(2) WITH 選択による出力列のカスタマイズ
declare @json2 as varchar(8000)
set @json2='{"myRoot":[
{"id":1178,"myObject":{"Plies":3,"Createtime":"2020-07-21T14:33:18.480"}},
{"id":1179,"myObject":{"Plies":3,"Createtime":"2020-07-21T14:36:27.457"}}
]}'
select * from openjson(@json2,'$.myRoot')
with(
id varchar(10) ,
Plies int '$.myObject.Plies',
Createtime datetime '$.myObject.Createtime'
);
2.Json関数
(1) ISJSON: 文字列に有効な JSON が含まれているかどうかをテストします。
print iif(isjson(@param) > 0, 'OK', 'NO');
2. JSON_VALUE: JSON 文字列からスカラー値を抽出します。
print json_value(@param, '$.info.address.town');
print json_value(@param, '$.info.tags[1]');
3. JSON_QUERY: JSON 文字列からオブジェクトまたは配列を抽出します。nvarchar(max) 型の JSON フラグメントを返します。
print json_query(@param, '$.info');
{
"type":1,
"address":{
"town":"Bristol",
"county":"Avon",
"country":"England"
},
"tags":["Sport", "Water polo"]
}
4. JSON_MODIFY: JSON 文字列の属性の値を更新し、更新された JSON 文字列を返します。
print json_modify(@param, '$.info.address.town', 'London');
戻る:
{
"info":{
"type":1,
"address":{
"town":"London",
"county":"Avon",
"country":"England"
},
"tags":["Sport", "Water polo"]
},
"type":"Basic"
}
デモコードの例
declare @param nvarchar(max);
set @param=N'{
"info":{
"type":1,
"address":{
"town":"Bristol",
"county":"Avon",
"country":"England"
},
"tags":["Sport", "Water polo"]
},
"type":"Basic"
}';
print iif(isjson(@param)>0, 'OK', 'NO');
print json_query(@param);
print json_value(@param, '$.info.address.town');
print json_value(@param, '$.info.tags[1]');
print json_query(@param, '$.info');
print json_query('["2020-1-8","2020-1-9"]');
print json_modify(@param, '$.info.address.town', 'London');
公式ドキュメント: https://learn.microsoft.com/zh-cn/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16