0

Here is my JSON:

[{"Key":"schedulerItemType","Value":"schedule"},{"Key":"scheduleId","Value":"82"},{"Key":"scheduleEventId","Value":"-1"},{"Key":"scheduleTypeId","Value":"2"},{"Key":"scheduleName","Value":"Fixed Schedule"},{"Key":"moduleId","Value":"5"}]

I want to query the database by FileMetadata column

I've tried this:

  SELECT * FROM FileSystemItems WHERE JSON_VALUE(FileMetadata, '$.Key') = 'scheduleId' and JSON_VALUE(FileMetadata, '$.Value') = '82'

but it doesn't work!

I had it working with just a dictionary key/value pair, but I needed to return the data differently, so I am adding it with key and value into the json now.

What am I doing wrong?

1 Answer 1

1

With the sample data given you'd have to supply an array index to query the 1th element (0-based array indexes), e.g.:

 select *
 from dbo.FileSystemItems
 where json_value(FileMetadata, '$[1].Key') = 'scheduleId'
 and json_value(FileMetadata, '$[1].Value') = '82'

If the scheduleId key can appear at arbitrary positions in the array then you can restructure the query to use OPENJSON instead, e.g.:

select *
from dbo.FileSystemItems
cross apply openjson(FileMetadata) with (
  [Key] nvarchar(50) N'$.Key',
  Value nvarchar(50) N'$.Value'
) j
where j.[Key] = N'scheduleId'
and j.Value = N'82'
Sign up to request clarification or add additional context in comments.

1 Comment

That was it!!! Thank you :-) I used the first item. It should always be at the 1 index (2nd item)

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.