1

I have the below Json string. I need to write a query to get the SP records. Without providing the index value, we need get the result.

 {
   "S": [
    {
      "Name": "Project1",
       "SP": [
        {
          "ID": 1,
          "Name": "Test1"
        },
        {
          "ID": 2,
          "Name": "Test2"
        },
  }]}

How do I query to get the SP values.

Expected Result:

 ID    Name 
 1     Test1 
 2     Test2

 I tried the below but not working. Can you please suggest the correct query.

SELECT DISTINCT JSON_VALUE(JsonData, '$.S[0].SP.ID') AS ID,
                JSON_VALUE(JsonData, '$.S[0].SP.Name') AS Name
    FROM TableA
2
  • which SQL engine are you using? Commented Apr 14, 2020 at 6:29
  • I am using SQL Server 2019 Commented Apr 14, 2020 at 6:49

1 Answer 1

0

You can use JSON_QUERY nested in OPENJSON function containing WITH Clause in order to visit all members of SP array dynamically :

SELECT ID, Name
  FROM TableA
 CROSS APPLY OPENJSON(JSON_QUERY(JsonData, '$.S[0].SP'))
             WITH (ID   nvarchar(500) '$.ID',
                   Name nvarchar(500) '$.Name')

Btw, you need to fix the JsonData as converting to

{
   "S": [
    {
      "Name": "0219 Project Methodology - Allergies",
       "SP": [
        {
          "ID": 1,
          "Name": "Test1"
        },
        {
          "ID": 2,
          "Name": "Test2"
        }
  ] } ] }

Demo

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

4 Comments

How we can query, if there was one more json object inside SP?
Hi @AshokYaganti , Can you add this as a new question containig a sample JSON, please ?
Sure @Barbaros Ozhan

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.