13

I have a stored procedure that query the database and store the result in a Json variable. Now I want to loop through the Json array by index to get a specific value. Can some tell me how to achieve this. Below is my query

 DECLARE @json NVARCHAR(Max)
 DECLARE @name VARCHAR(50) = 'Name'

 SET @json = (select name from getalldataView where 
 SOUNDEX(name) LIKE SOUNDEX(@name) FOR JSON PATH, ROOT('Names'))

 DECLARE @i int = 0

 WHILE @i < lengthOFArray
 BEGIN
       SET @i = @i + 1;

   SELECT value
   FROM OPENJSON(@json, '$.Names[',@i,']');

 END
1

4 Answers 4

7

source Here

sample data

{ "type": "MultiPolygon", 
    "coordinates": [
        [
            [[40, 40], [20, 45], [45, 30], [40, 40]]
        ], 
        [
            [[20, 35], [10, 30], [10, 10], [30, 5], [45, 20], [20, 35]], 
            [[30, 20], [20, 15], [20, 25], [30, 20]]
        ]
    ]
}

Sql Code

SELECT polygons.[key] as polygon, lines.[key] as line, x, y
FROM OPENJSON(@multipolygon, '$.coordinates') as polygons
       CROSS APPLY OPENJSON(polygons.value) as lines
              CROSS APPLY OPENJSON(lines.value)
                     WITH (x float '$[0]', y float '$[1]')
Sign up to request clarification or add additional context in comments.

Comments

4

Something like this will work as of SQL Server 2017.

        SET @i = 0;

        SET @length = 
        (SELECT COUNT(*) 
         FROM OPENJSON(@json,'$.names'))
        WHILE @i < @length
        BEGIN
            DECLARE @driverName NVARCHAR(100);
            SET @driverName = JSON_VALUE(@json,CONCAT('$.names[',@i,']'))
            -- do stuff here like call stored proc...
            SET @i = @i +1;
        END

If you don't need to call a stored proc, but just need to modify the JSON in some way you may find this useful. https://stackoverflow.com/a/59293083/7446265

1 Comment

The issue on above solution is JSON_VALUE(@json,CONCAT('$.names[',@i,']')). We can't use CONCAT on Path of JSON_VALUE
3

Screenshot of result

I this example have multi layer json data and using cross join getting those in one table result

 declare @jsondata nvarchar(max);
    set @jsondata ='{"id":1,"planTypeId":0,"locationId":0,"auditId":0,"empId":0,"accessID":"string","actionItem":"string","resUserID":0,"createdDate":"2019-09-12T13:22:23.805Z","dueDate":"2019-09-12T13:22:23.805Z","lastModified":"2019-09-12T13:22:23.805Z","completedDate":"2019-09-12T13:22:23.805Z","completedBy":0,"status":0,"desc":"string","relQuestionID":0,"catID":0,"equipmentID":0,"steps":[{"id":1,"trnPlanId":1,"dueDate":"2019-09-12T13:22:23.805Z","type":1,"quizId":0,"taskId":0,"docCourseUrl":"string","users":[{"id":1,"empId":1,"status":true}]},{"id":2,"trnPlanId":2,"dueDate":"2019-09-12T13:22:23.805Z","type":2,"quizId":0,"taskId":0,"docCourseUrl":"string","users":[{"id":2,"empId":2,"status":true},{"id":3,"empId":3,"status":true}]}]}';



    SELECT
        JSON_Value (c.value, '$.id') as Id, 
        JSON_Value (c.value, '$.type') as planTypeId, 
        JSON_Value (p.value, '$.id') as userId, 
        JSON_Value (p.value, '$.empId') as empId

    FROM OPENJSON (@jsondata, '$.steps') as c
    CROSS APPLY OPENJSON (c.value, '$.users') as p


    SELECT
        JSON_Value (c.value, '$.id') as Id, 
        JSON_Value (c.value, '$.type') as planTypeId

    FROM OPENJSON (@jsondata, '$.steps') as c

Comments

0

when you begin end your query to select openjson , could you add one more column , and the value is your looping index. so you can add another Where validation inside the begin end . OpenJSON read all your json and insert it to new row.

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.