Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2016 select where in json array

I have a table [JsonTable], and the column [JsonData] save the json string,

JsonData like:

{
   "Names": ["John", "Joe", "Sam"]
}

How can I inner join this table like:

SELECT* FROM [TestTable] AS T
INNER JOIN [JsonTable] AS J ON T.[Name] IN JSON_QUERY(J.[JsonData], '$.Names')
like image 800
Max Avatar asked Oct 12 '17 03:10

Max


People also ask

How can I get specific data from JSON in SQL?

To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).

How can I get specific data from JSON?

Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.

Does SQL Server 2016 support JSON?

SQL Server 2016 is finally adding support for JSON, a lightweight format for exchanging data between different source types, similar to how XML is used.

What is Json_value in SQL?

SQL/JSON function json_value selects JSON data and returns a SQL scalar or an instance of a user-defined SQL object type or SQL collection type (varray, nested table). If json_value targets a single scalar JSON value then it returns a scalar SQL value. You can specify the SQL data type for the returned scalar value.


2 Answers

You need to use OPENJSON function for reading Names array. You can use this query.

SELECT * FROM [TestTable] T
INNER JOIN [JsonTable] AS J ON T.[Name] IN (SELECT value FROM OPENJSON(J.[JsonData],'$.Names'))
like image 50
Serkan Arslan Avatar answered Oct 11 '22 15:10

Serkan Arslan


Another way is to use the cross apply operator like this:

SELECT *
FROM [JsonTable] AS J
CROSS APPLY OPENJSON(J.[JsonData], '$.Names') jsonValue
INNER JOIN [TestTable] T ON T.[Name] = jsonvalue.value  
like image 20
Lydia Avatar answered Oct 11 '22 15:10

Lydia