The JSON object structure is:
{
"store": {
"storeId":123,
"operations": {
"seasons": [
{
"storeHours": [{},{},{}] // consider it has 3 objects
},
{
"storeHours": [{},{}] //consider it has 2 objects
}
]
}
}
}
I want to count the size of "storeHours". I tried with:
DECLARE @count INT = 0;
DECLARE @destination NVARCHAR = (N'$.store.operations.seasons[' + @count + N'].storeHours');
Also tried with:
DECLARE @destination NVARCHAR = CONCAT(N'$.store.operations.seasons[', @count, N'].storeHours');
DECLARE @storeHoursCount INT = (
select count(A.[key]) as [count]
from (VALUES(@json)) V(J)
CROSS APPLY OPENJSON(V.J) WITH(
[storeHours] nvarchar(MAX) @destination AS JSON) S
CROSS APPLY OPENJSON(S.storeHours) A
);
I get an error:
Incorrect syntax near '@destination'
This works:
DECLARE @storeHoursCount INT = (
select count(A.[key]) as [count]
from (VALUES(@json)) V(J)
CROSS APPLY OPENJSON(V.J) WITH (
[storeHours] nvarchar(MAX) '$.store.operations.seasons[0].storeHours' AS JSON
) S
CROSS APPLY OPENJSON(S.storeHours) A
);
But I want it to be dynamic. Is there something that I am missing? Also what can be the reason for CONCAT() not working?
EDIT: @Zhorov solution works really good when we want over all count of storeHours present. i.e Sum of all storeHours present in all seasons.
My requirement is to get count of storeHours based upon index season (eg: season[0]). How can this be achieved?
seasonsis also a JSON array, so you have nested JSON arrays. Which count do you want?storeHours