Closed. This question needs details or clarity . It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post .
Closed 21 days ago.
Improve this question
I have a nvarchar(max) column that contains a string array of tags. I am querying this columns for matching values using the JSON functions. While I do have it working, I wasn't sure if there was a better way using other built-in functions.
IF(NOT EXISTS(SELECT 1 FROM #temp))
BEGIN
CREATE TABLE #temp (Id int IDENTITY, Tags nvarchar(max));
INSERT INTO #temp (Tags) VALUES ('["red", "blue", "green"]');
INSERT INTO #temp (Tags) VALUES ('["red", "yellow", "blue"]');
INSERT INTO #temp (Tags) VALUES ('["red", "purple", "orange"]');
END
SELECT * FROM #temp CROSS APPLY OPENJSON(Tags) WITH (T nvarchar(100) '$') tags WHERE tags.T = 'red';
SELECT * FROM #temp CROSS APPLY OPENJSON(Tags) WITH (T nvarchar(100) '$') tags WHERE tags.T = 'blue';
I've seen quite a few ways to query JSON data and wasn't sure if this was the best practice for querying this data. JSON_QUERY uses a $.property format that I don't have because this is a simple single-dimension array.
Is there a better way?
1条答案
按热度按时间lnlaulya1#
We can use the fact that OPENJSON returns 3 columns:
key
,value
andtype
.Example query:
SELECT * FROM OPENJSON('["v1", "v2", "v3"]')
Output:
We can use this to construct the query:
Output of first query is data row 1 because its JSON contains a value that is equal to
'v2'
:Output of second query is data rows 1 and 3 because they match
'v1'
or'v2'
or'z3'
: