前面有一篇《在SQL中直接把查詢結果轉換爲JSON數據》http://www.javashuo.com/article/p-moiuvqib-da.html,是把table轉換爲json。html
現反過來,當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說明:json
SELECT [key],[value],[type],[dbo].[svf_JSONDataType]([type]) AS data_type FROM OPENJSON (@json_text)
下面是真正把JSON轉TABLE:ide
SELECT [type],[desc] FROM OPENJSON (@json_text ,'$."DB Type"') WITH ( [type] NVARCHAR(20) '$.type', [desc] NVARCHAR(40) '$.desc' )