[英]Extract data from Json string and divide into multiple columns
I have a column in a table that has Jsonstring text: 我在具有Jsonstring文本的表中有一列:
[
{
"PType":{"code":"9","name":"Hospitality"},
"PSubType":{"code":"901","name":"Hotel"},
"AType":{"code":"9","name":"Hospitality"},
"ASubType":{"code":"901","name":"Hotel"}
}
]
How can I divide that into multiple columns using sql server query? 如何使用SQL Server查询将其分为多个列?
With SQL-Server 2016+ there is native JSON support : 借助SQL-Server 2016+, 本机JSON支持 :
DECLARE @json NVARCHAR(MAX)=
N'[
{
"PType":{"code":"9","name":"Hospitality"},
"PSubType":{"code":"901","name":"Hotel"},
"AType":{"code":"9","name":"Hospitality"},
"ASubType":{"code":"901","name":"Hotel"}
}
]';
SELECT A.[key]
,JSON_VALUE(A.value,'$.code') AS Code
,JSON_VALUE(A.value,'$.name') AS [Name]
FROM OPENJSON(JSON_QUERY(@json,'$[0]')) A;
The result 结果
key Code Name
---------------------------------
PType 9 Hospitality
PSubType 901 Hotel
AType 9 Hospitality
ASubType 901 Hotel
With JSON_QUERY()
you can get the element within the array, OPENJSON
will find all objects within and return them as derived table. 使用
JSON_QUERY()
您可以获取数组中的元素, OPENJSON
将在其中查找所有对象,并将它们作为派生表返回。
JSON_VALUE
will read the internals into columns. JSON_VALUE
将内部信息读入列。
with a version below v2016 you should use another tool or think about a CLR function... 对于v2016以下的版本,您应该使用其他工具或考虑CLR功能...
In SQL Server 2016+ you can use a combination of openjson
(more info here ) and cross apply
: 在SQL Server 2016+中,您可以结合使用
openjson
(更多信息在此处 )和cross apply
:
declare @json nvarchar(max) = '[ { "PType":{"code":"9","name":"Hospitality"}, "PSubType":{"code":"901","name":"Hotel"}, "AType":{"code":"9","name":"Hospitality"}, "ASubType":{"code":"901","name":"Hotel"} } ]'
select
[PT].[code] as Ptype_Code
,[PT].[name] as Ptype_Name
,[PS].[code] as PSubType_Code
,[PS].[name] as PSubType_Name
,[AT].[code] as AType_Code
,[AT].[name] as AType_Name
,[AS].[code] as ASubType_Code
,[AS].[name] as ASubType_Name
from openjson (@json)
with
(
PType nvarchar(max) as json,
PSubType nvarchar(max) as json,
AType nvarchar(max) as json,
ASubType nvarchar(max) as json
) as lev1
cross apply openjson (lev1.PType)
with
(
code int,
name nvarchar(100)
) as PT
cross apply openjson (lev1.PSubType)
with
(
code int,
name nvarchar(100)
) as PS
cross apply openjson (lev1.AType)
with
(
code int,
name nvarchar(100)
) as [AT]
cross apply openjson (lev1.ASubType)
with
(
code int,
name nvarchar(100)
) as [AS]
Result: 结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.