0

I have a column in a table that has Jsonstring text:

[
    {
        "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?

2 Answers 2

2

With SQL-Server 2016+ there is native JSON support:

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

Some explanation:

With JSON_QUERY() you can get the element within the array, OPENJSON will find all objects within and return them as derived table.

JSON_VALUE will read the internals into columns.

Hint

with a version below v2016 you should use another tool or think about a CLR function...

Sign up to request clarification or add additional context in comments.

Comments

0

In SQL Server 2016+ you can use a combination of openjson (more info here) and 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:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.