Search code examples
sqljsonsql-serversql-server-2017json-query

SQL find elements is in JSON array column


Hello i have a column table who contains json array with tags in it, I try to find a way to select result who contain some of values in it :

ID tags
1 ["test01"]
2 ["test02","test03"]

I try to used JSON_QUERY AND JSON_VALUE():

SELECT *
FROM table_tags  
WHERE JSON_QUERY(tags,'$') IN ('test01', 'test02')

return nothing

but with json_value on the first array element [0]

SELECT *
FROM table_tags  
WHERE JSON_VALUE(tags,'$[0]') IN ('test01', 'test02')

it return the first one with test01

ID tags
1 ["test01"]

i need to find a way to iterate through json_value tags to find all tags in ('test01', 'test02')


Solution

  • You need an OPENJSON() call to parse the stored JSON array. The result is a table with columns key, value and type and in the value column is each element from the parsed JSON array. The column data type is nvarchar(max) with the same collation as tags column collation.

    SELECT *
    FROM (VALUES
       (1, '["test01"]'),
       (2, '["test02","test03"]')
    ) table_tags (id, tags)
    WHERE EXISTS (
       SELECT 1 FROM OPENJSON(tags) WHERE [value] IN ('test01', 'test02')
    )