前面有一篇《在SQL中直接把查詢結果轉換為JSON數據》https://www.cnblogs.com/insus/p/10905566.html,是把table轉換為json。 現反過來,當SQL從前端接收過來的數據是JSON的話,需要把它轉換為TABLE。在MS SQL Server 2016有 ...
前面有一篇《在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