You know about the new JSON_ support in SQL Server 2016 so let's say I have this data in a row
{ "BaseBoarding": 1, "PriceLineStrategy": "PerPersonPerNight", "Currency": "EUR", "BasePriceLineList": [ { "RoomTypeId": 1, "PeriodId": 1, "Price": 10.0 }, { "RoomTypeId": 1, "PeriodId": 2, "Price": 100.0 }, { "RoomTypeId": 1, "PeriodId": 3, "Price": 190.0 }, { "RoomTypeId": 2, "PeriodId": 1, "Price": 280.0 }, { "RoomTypeId": 2, "PeriodId": 2, "Price": 310.0 }, { "RoomTypeId": 2, "PeriodId": 3, "Price": 340.0 } ] }
How do I get the number of items of "BasePriceLineList" in the most performant way, preferably using the built-in JSON support?
Need to write something like this:
SELECT JSON_ARRLEN(JsonDataCol, '$.BasePriceline') FROM MyTable WHERE Id = 1
and get 6 as the result.
To obtain the size of a JSON-encoded array or object, use the json_size function, and specify the column containing the JSON string and the JSONPath expression to the array or object.
You can use the LEN function () to find the length of a string value in SQL Server, for example, LEN (emp_name) will give you the length stored in the emp_name string. Remember that this is different from the actual length you specified when creating the table, for example, emp_name VARCHAR (60).
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).
Using a table instead of a variable:
SELECT count(priceLineLists.RoomTypeId) FROM Mytable CROSS APPLY OPENJSON (JsonDataCol, N'$.BasePriceLineList') WITH ( RoomTypeId int) AS priceLineLists
You can convert it to a data set and then count the rows:
DECLARE @JSON NVARCHAR(4000) = N'{ "BaseBoarding": 1, "PriceLineStrategy": "PerPersonPerNight", "Currency": "EUR", "BasePriceLineList": [ { "RoomTypeId": 1, "PeriodId": 1, "Price": 10.0 }, { "RoomTypeId": 1, "PeriodId": 2, "Price": 100.0 }, { "RoomTypeId": 1, "PeriodId": 3, "Price": 190.0 }, { "RoomTypeId": 2, "PeriodId": 1, "Price": 280.0 }, { "RoomTypeId": 2, "PeriodId": 2, "Price": 310.0 }, { "RoomTypeId": 2, "PeriodId": 3, "Price": 340.0 } ] }' select COUNT(*) FROM OPENJSON(@json, N'$.BasePriceLineList') WITH (RoomTypeID varchar(100) '$.RoomTypeId')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With