Reputation: 261
I am trying to use OpenJSON at JSON data but it is not producing the result as expected. DB JSON in field_data is:
{
"name":"Test",
"Cell-Number":"Test",
"CNIC":"12112112",
"Person-Name":"Test",
"Focal-person-cell-phone":"121212",
"Focal-person-CNIC":"12121212",
"Religion":"Test",
"Total-teachers":"4",
"Total-students":"37",
"Total-Hosteled-students":"11",
"Government-\/-Private":"Govt",
"Category":"Jamia",
"Total-Gates":"3",
"Registration-number":"211121",
"Security-guard\/watchman":"10",
"Condition":"Test"
}
I am trying to fetch the data where name is equal to Test in field_data column. My Query to fetch data is ;
SELECT *
FROM beat_data
WHERE EXISTS (
Select *
FROM OPENJSON(field_data,'$.name')
WHERE Value = 'Test'
)
I have feelings that I am not using the path properly.
Upvotes: 1
Views: 311
Reputation: 29943
You may try to use JSON_VALUE()
:
Input:
CREATE TABLE #BeatData (
JsonColumn nvarchar(max)
)
INSERT INTO #BeatData
(JsonColumn)
VALUES
(N'{
"name":"Test",
"Cell-Number":"Test",
"CNIC":"12112112",
"Person-Name":"Test",
"Focal-person-cell-phone":"121212",
"Focal-person-CNIC":"12121212",
"Religion":"Test",
"Total-teachers":"4",
"Total-students":"37",
"Total-Hosteled-students":"11",
"Government-\/-Private":"Govt",
"Category":"Jamia",
"Total-Gates":"3",
"Registration-number":"211121",
"Security-guard\/watchman":"10",
"Condition":"Test"
}')
T-SQL:
SELECT *
FROM #BeatData
WHERE JSON_VALUE(JsonColumn, '$.name') = N'Test'
If you want to get JSON
data as result set, try with the following:
SELECT j.*
FROM #BeatData b
CROSS APPLY OPENJSON(b.JsonColumn) WITH (
name varchar(100) '$.name',
[Cell-Number] varchar(100) '$."Cell-Number"',
CNIC varchar(100) '$.CNIC',
[Person-Name] varchar(100) '$."Person-Name"',
[Focal-person-cell-phone] varchar(100) '$."Focal-person-cell-phone"',
[Focal-person-CNIC] varchar(100) '$."Focal-person-CNIC"',
Religion varchar(100) '$.Religion',
[Total-teachers] varchar(100) '$."Total-teachers"',
[Total-students] varchar(100) '$."Total-students"',
[Total-Hosteled-students] varchar(100) '$."Total-Hosteled-students"',
[Government-\/-Private] varchar(100) '$."Government-\/-Private"',
Category varchar(100) '$.Category',
[Total-Gates] varchar(100) '$."Total-Gates"',
[Registration-number] varchar(100) '$."Registration-number"',
[Security-guard\/watchman] varchar(100) '$."Security-guard\/watchman"',
Condition varchar(100) '$.Condition'
) j
WHERE j.name = N'Test'
Upvotes: 3