0

Is it possible to run queries on array elements? Seems like it works ok on the top level items... Lets say I have this json:

{
  "_id": "5769cfbf7e45b52e388bbc78",
  "address": {
    "street": "2 Avenue",
    "zipcode": "10075",
    "building": "1480",
    "coord": [
      73.9557413,
      40.7720266
    ]
  },
  "borough": "Manhattan",
  "cuisine": "Italian",
  "grades": [
    {
      "date": "2014-10-01T00:00:00.000Z",
      "grade": "A",
      "score": 11
    },
    {
      "date": "2014-01-06T00:00:00.000Z",
      "grade": "B",
      "score": 17
    }
  ],
  "name": "Vella",
  "restaurant_id": "41704620"
}

Is it possible to use JSON_QUERY / JSON_VALUE to do a where clause against grades[xxx].score? I.e. I want to return all documents where ANY of the grades.score is >= 17.

1
  • I think you want to use OPENJSON. I don't have SQL Server 2016 available, so I can't really help any further than that. Commented Jun 24, 2016 at 2:26

1 Answer 1

2

SQL Azure and SQL Server 2016 supports JSON natively now. You can use the following query in 'EXISTS' clause, or whatever is needed (assuming @json contains the given JSON data):

SELECT g.score as score
FROM OPENJSON(@json) WITH (Id varchar(max)) j
    CROSS APPLY OPENJSON(JSON_QUERY(@json, '$.grades')) WITH (score int) AS g
WHERE g.score = 17
Sign up to request clarification or add additional context in comments.

1 Comment

SQL Azure and SQL Server 2016 supports JSON natively.

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.