So let's say I have a varchar column in a table with some structure like:
{
"Response":{
"DataArray":[
{
"Type":"Address",
"Value":"123 Fake St"
},
{
"Type":"Name",
"Value":"John Doe"
}
]
}
}
And I want to create a persisted computed column on the "Value" field of the "DataArray" array element that contains a Type field that equals "Name". (I hope I explained that properly. Basically I want to index the people's names on that structure).
The problem is that, unlike with other json objects, I can't use the JSON_VALUE
function in a straightforward way to extract said value. I've no idea if this can be done, I've been dabbling with JSON_QUERY
but so far I've no idea what to do.
Any ideas and help appreciated. Thanks!
3条答案
按热度按时间dgiusagp1#
You could achieve it using function:
Defining table:
Sample data:
db<>fiddle demo
qvk1mo1f2#
You could use a computed column with PATINDEX and index that:
5hcedyr03#
You could use a scalar function as @Lukasz Szozda posted - it's a good solution for this. The problem, however, with T-SQL scalar UDFs in computed columns is that they destroy the performance of any query that table is involved in. Not only does data modification (inserts, updates, deletes) slow down, any execution plans for queries that involve that table cannot leverage a parallel execution plan. This is the case even when the computed column is not referenced in the query. Even index builds lose the ability to leverage a parallel execution plan. Note this article: Another reason why scalar functions in computed columns is a bad idea by Erik Darling.
This is not as pretty but, if performance is important than this will get you the results you need without the drawbacks of a scalar UDF.
Note that, this works well for the structure you posted. It may need to be tweaked depending on what the JSON does and can look like.
A second (and better but more complex) solution would be to take the json path logic from Lukasz Szozda's scalar UDF and get it into a CLR. T-SQL scalar UDFs, when written correctly, do not have the aforementioned problems that T-SQL scalar UDFs do.