Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query JSON inside SQL Server 2012 column

I have a column inside my SQL Server 2012 table which contains following Json data.

[{"bvin":"145a7170ec1247cfa077257e236fad69","id":"b06f6aa5ecd84be3aab27559daffc3a4"}]

Now I want to use this column data in my query like

select * 
from tb1 
left join tb2 on tb1.(this bvin inside my column) = tb2.bvin.

Is there a way to query JSON data in SQL Server 2012?

like image 631
isumit Avatar asked May 18 '14 15:05

isumit


2 Answers

Honestly, this is a terrible architecture for storing the data, and can result in some serious performance issues.

If you truly don't have control to change the database, you can accomplish this by parsing out the value with SUBSTRING like below, but it's leading down a very unhappy path:

SELECT *
FROM tb1
JOIN tb2 on tb2.bvin = 
    SUBSTRING(
        tb1.json
        ,CHARINDEX('"bvin":"', tb1.json) + LEN('"bvin":"')
        ,CHARINDEX('"', tb1.json, CHARINDEX('"bvin":"', tb1.json) + LEN('"bvin":"')) - CHARINDEX('"bvin":"', tb1.json) - LEN('"bvin":"')
    )

And sadly, that's as easy as it can be.

like image 178
arserbin3 Avatar answered Sep 29 '22 09:09

arserbin3


Another solution is JSON Select which providers a JsonNVarChar450() function. Your example would be solved like so:

select * 
from tb1 
left join tb2 on dbo.JsonNVarChar450(tb1.YourColumnName, 'bvin') = tb2.bvin

as someone mentioned, this could be a bit slow, however you could add an index using the JSON Select function like so:

alter table tb2 add
bvin as dbo.JsonNVarChar450(YourColumnName, 'bvin') persisted

go

create index IX_tb2_bvin on tb2(bvin)

And from then on you can query using the index over the computed column bvin, like so:

select * 
from tb1 
left join tb2 on tb1.bvin = tb2.bvin

DISCLOSURE: I am the author of JSON Select, and as such have an interest in you using it :)

like image 27
joshuahealy Avatar answered Sep 29 '22 10:09

joshuahealy