前面有一篇《在SQL中直接把查询结果转换为JSON数据》https://www.cnblogs.com/insus/p/10905566.html,是把table转换为json。
现反过来,当SQL从前端接收过来的数据是JSON的话,需要把它转换为TABLE。在MS SQL Server 2016有一个方法,OPENJSON。
DECLARE @json_text NVARCHAR(MAX)
SET @json_text =
N'
{
"DB Type":
[
{"type":"AF","desc":"聚合函数(CLR)"},
{"type":"F","desc":"FOREIGN KEY 约束"},
{"type":"FN","desc":"SQL 标量函数"},
{"type":"FS","desc":"程序集(CLR)标量函数"},
{"type":"FT","desc":"程序集(CLR)表值函数"},
{"type":"RF","desc":"复制筛选过程"},
{"type":"IF","desc":"SQL 内联表值函数"},
{"type":"TF","desc":"SQL 表值函数"}
]
}'
读取JSON文本的key,value,type和type说明:
SELECT [key],[value],[type],[dbo].[svf_JSONDataType]([type]) AS data_type FROM
OPENJSON (@json_text)
Source Code
下面是真正把JSON转TABLE:
SELECT [type],[desc] FROM
OPENJSON (@json_text ,'$."DB Type"')
WITH
(
[type] NVARCHAR(20) '$.type',
[desc] NVARCHAR(40) '$.desc'
)
Source Code