How to insert all array elements in one field in SQL Server? - arrays

I have a column named "RecordIds". I am importing data from json to sql server . I have this json file. but when i inserted all in table but in last three fields i got no value in database table. how can i solve this problem ?
{
"Id": 1,
"ImageName": "person1",
"PersonName": "C1-C4:stretch",
"GroupId": 1,
"Text": "Sam has complete C4 tetraplegia. He sits in his power wheelchair all day and is unable to move his arms.<br/><br/>The aim of Sam`s programme is to prevent contracture.<br/><br/>This programme is suitable for people with C1-C4 tetraplegia.",
"RecordIds": [511, 517, 569, 571, 688, 1037],
"DropdownIds": [1, 56, 58],
"TextTitleIds": [3, 5, 7]
}
here is my query
declare #details varchar(max)
select #details =
BulkColumn
from openrowset(BULK'D:\JSON\mmh\examples.json', single_blob) json
if(ISJSON(#details) = 1)
begin
print 'Valid Json'
insert into [dbo].[Examples]
select * from
openjson(#details, '$.example')
with(
id smallint '$.Id',
[ImageName] varchar(50) '$.ImageName',
[PersonName] varchar(50) '$.PersonName',
[GroupId] smallint '$.GroupId',
[Text] varchar(50) '$.Text',
[RecordIds] varchar(50) '$.RecordIds',
[DropdownIds] varchar(50) '$.DropdownIds',
[TextTitleIds] varchar(50) '$.TextTitleIds'
)
end
else
begin
print 'invalid Json'
end
i got this output
RecordIds DropdownIds TextTitleIds
NULL NULL NULL

You need to use AS JSON, eg
declare #json nvarchar(max) =
'{
"example":
{
"Id": 1,
"ImageName": "person1",
"PersonName": "C1-C4:stretch",
"GroupId": 1,
"Text": "Sam has complete C4 tetraplegia. He sits in his power wheelchair all day and is unable to move his arms.<br/><br/>The aim of Sam`s programme is to prevent contracture.<br/><br/>This programme is suitable for people with C1-C4 tetraplegia.",
"RecordIds": [511, 517, 569, 571, 688, 1037],
"DropdownIds": [1, 56, 58],
"TextTitleIds": [3, 5, 7]
}
}'
select * from
openjson(#json, '$.example')
with(
id smallint '$.Id',
[ImageName] varchar(50) '$.ImageName',
[PersonName] varchar(50) '$.PersonName',
[GroupId] smallint '$.GroupId',
[Text] varchar(50) '$.Text',
[RecordIds] nvarchar(MAX) '$.RecordIds' as json,
[DropdownIds] nvarchar(MAX) '$.DropdownIds' as json,
[TextTitleIds] nvarchar(MAX) '$.TextTitleIds' as json
)

Related

How to use OPENJSON to concatenate json Array in a column of a table

I have a column in SQL table which has a string value denoting a JSON array. I need to concatenate the array for comparison. There are multiple rows of this data and will be using a CURSOR to iterate through a set of values because no example of using using OPENJSON on a column is available
there are solutions for iterating the array in a property ('$.list') of a JSON but nothing which talks about a direct array.
from:
ID
Value
1
[{"id": 1, "val":"j"}, {"id": 2,"val":"o"}, {"id": 3, "val":"h"}, {"id": 4, "val":"h";}, {"id": 5, "val":"n"}]
2
[{"id": 1, "val":"d"}, {"id": 2,"val":"o"}, {"id": 3, "val":"e"}]
Result:
ID
Result
1
john
2
doe
and then proceed with my other iteration logic on the Result table
If you correct the example JSON by switching the " and ' characters around you could get your desired results by way of string_agg() and openjson()...
declare #Table table (
ID int,
[Value] nvarchar(max)
);
insert #Table (ID, [Value]) values
(1, N'[{"id": 1, "val":"j"}, {"id": 2,"val":"o"}, {"id": 3, "val":"h"}, {"id": 4, "val":"h"}, {"id": 5, "val":"n"}]'),
(2, N'[{"id": 1, "val":"d"}, {"id": 2,"val":"o"}, {"id": 3, "val":"e"}]');
select ID, string_agg(J.[val], N'') as [Result]
from #Table
cross apply openjson([Value]) with (
[val] nvarchar(50)
) J
group by ID;
ID
Result
1
johhn
2
doe

With SQL 2017 -- does OPENJSON remove the escape sequences from the raw JSON data

SQL proc consuming JSON payload from Web Service but the data was escaped before being received in the procedure. I have a payload like this:
{
"RES_NBR_ID": "00000056566",
"RES_SCRIPT_NM": "Test Script",
"RES_SCRIPT_ID": "jcet2",
"RES_RESULT_GROUP_ID": 42622528,
"RES_CREATED_BY_ID": "Jcccc",
"RES_QUESTION_TXT": "asdf",
"RES_ANSWER_TXT": "asdfa\"asfasf",
"SORT_NBR": 4,
"RES_QUESTION_ID": 4,
"RES_DELETED_BY_ID": ""
}
You'll notice that the ANSWER_TXT is really asdfa"asfasf
The backslash was put in by the JSON.stringify function on the service
So will using OPENJSON like the following remove all stringfy sequences:
SELECT (SELECT MAX(RES_ID) FROM SCRT_RESULTS) + ROW_NUMBER() OVER(ORDER BY RES_QUESTION_TXT) AS RES_ID
,RES_NBR_ID
,RES_SCRIPT_NM
,RES_QUESTION_TXT
,RES_ANSWER_TXT
,RES_CREATED_BY_ID
,getdate() [RES_CREATED_DT]
,RES_DELETED_BY_ID
,getdate() [RES_DELETED_DT]
,RES_RESULT_GROUP_ID
,RES_SORT_NBR
,RES_SCRIPT_ID
,RES_QUESTION_ID
,getUTCdate() [RES_CREATED_UTC_DT]
from openjson(#json_result)
WITH(
RES_NBR_ID varchar(16)
,RES_SCRIPT_NM varchar(150)
,RES_SCRIPT_ID varchar(5)
,RES_RESULT_GROUP_ID bigint
,RES_CREATED_BY_ID varchar(20)
,RES_QUESTION_TXT varchar(2000)
,RES_ANSWER_TXT varchar(2000)
,RES_SORT_NBR int
,RES_QUESTION_ID int
,RES_DELETED_BY_ID varchar(20)
)

How can I read below Json column stored in SQL Server using openjson?

Declare #ResponseText nvarchar(4000)
set #responseText ='{
"submissions": [
{
"xml_id":"id_x5d94851726b470.68571510",
"fields": [
{"fieldvalue":"customerEmail#xyzdomain.com","fieldid":"57282490"},
{"fieldvalue":"123","fieldid":"57282423"},
{"fieldvalue":"12345-678900","fieldid":"57282500"},
{"fieldvalue":"Test Message here ","fieldid":"57282564"}
]
}
]
}'
SELECT *
FROM OPENJSON (#ResponseText, '$.submissions') WITH (
ID NVARCHAR(100) '$.xml_id',
$.fields.field NVARCHAR(100) ...
)
etc rest of all the record? I got "NULL" for the rest fields under fields array
You can try it like this:
Declare #ResponseText nvarchar(4000)
set #responseText ='{
"submissions": [
{
"xml_id":"id_x5d94851726b470.68571510",
"fields": [
{"fieldvalue":"customerEmail#xyzdomain.com","fieldid":"57282490"},
{"fieldvalue":"123","fieldid":"57282423"},
{"fieldvalue":"12345-678900","fieldid":"57282500"},
{"fieldvalue":"Test Message here ","fieldid":"57282564"}
]
}
]
}'
--The query
SELECT A.ID
,B.*
FROM OPENJSON (#ResponseText, '$.submissions')
WITH (ID NVARCHAR(100) '$.xml_id'
,fields NVARCHAR(MAX) AS JSON) A
OUTER APPLY OPENJSON(a.fields)
WITH(fieldvalue NVARCHAR(150)
,fieldid BIGINT) B;
The result
ID fieldvalue fieldid
id_x5d94851726b470.68571510 customerEmail#xyzdomain.com 57282490
id_x5d94851726b470.68571510 123 57282423
id_x5d94851726b470.68571510 12345-678900 57282500
id_x5d94851726b470.68571510 Test Message here 57282564
The idea in short:
You started correctly using the WITH-clause to read the xml_id. The property fields is nothing else than another element on the same level. But we return it AS JSON. This will allow to add another APPLY OPENJSON(), pass in the fragment we got from $.fields and use another WITH-clause to get the two properties of the objects within the array.

OPENJSON unable to parse Chinese characters

I'm trying to convert my JSON data into a table format in SQL Server.
Following are my JSON data:
[{
"emp_no": "001",
"emp_designation":"Data Admin",
"emp_name": "Peter",
"emp_name2": "彼特"
},
{
"emp_no": "002",
"emp_designation":"Software Engineer",
"emp_name": "Lee",
"emp_name2": "李"
}]
What I had tried are:
DECLARE #JSON NVARCHAR(MAX)
set #JSON='[{
"emp_no": "001",
"emp_designation":"Data Admin",
"emp_name": "Peter",
"emp_name2": "彼特"},
{
"emp_no": "002",
"emp_designation":"Software Engineer",
"emp_name": "Lee",
"emp_name2": "李"
}]'
--Method 1
SELECT * INTO #emp_temp FROM OPENJSON(#JSON)
WITH (emp_no varchar(20),
emp_designation varchar(50),
emp_name NVARCHAR(100),
emp_name2 NVARCHAR(100))
SELECT * FROM #Emp_temp
DROP TABLE #Emp_temp
--Method 2
SELECT
JSON_Value (EMP.VALUE, '$.emp_no') as emp_no,
JSON_Value (EMP.VALUE, '$.emp_designation') as emp_designation,
JSON_Value (EMP.VALUE, '$.emp_name') as emp_name,
JSON_Value (EMP.VALUE, '$.emp_name2') as emp_name2
INTO #Emp_temp2
FROM OPENJSON (#JSON) as EMP
SELECT * FROM #Emp_temp2
DROP TABLE #Emp_temp2
However, both temp table return me following result, with the Chinese characters remain as "???".
Temp table select result
emp_no emp_designation emp_name emp_name2
001 |Data Admin | Peter| ??
002 |Software Engineer| Lee | ?
Any idea how to preserve the original Chinese characters after parse the data into temp table?
Thanks.
*Edit:
I know it can work by putting a extra 'N' in front of the JSON
set #JSON=N'[
{ "emp_no": "001...
.....
But actually the JSON is a parameter in a Store Procedure, I cannot simply add a N like : set #JSON = 'N' + #JSON,
which this will jeopardize the format of the JSON data, and cause an error.
ALTER PROCEDURE [dbo].[SP_StoreEmpInfo]
#JSON NVARCHAR(max)
#JSON = 'N' + #JSON
/*Will cause invalid JSON format error */
SELECT
JSON_Value (EMP.VALUE, '$.emp_no') as.....
Try adding 'N' before your sql set to indicate that unicode characters are contained within like this:
DECLARE #JSON NVARCHAR(MAX)
set #JSON=N'[{
"emp_no": "001",
"emp_designation":"Data Admin",
"emp_name": "Peter",
"emp_name2": "彼特"},
{
"emp_no": "002",
"emp_designation":"Software Engineer",
"emp_name": "Lee",
"emp_name2": "李"
}]'
This question may assist in background:
What does N' stands for in a SQL script ? (the one used before characters in insert script)

SQL Server: select rows which has particular id in their json column

I have a table with two columns: [ID] and [Content] (with ISJSON constraint, so every row must have valid JSON in [Content] column).
These JSONs have an array field, which consists of objects with some specific ID (and many more fields) .
{
"departments": [ { "id": 1, "fieldA": "somevalue" },
{ "id": 2, "fieldA": "somevalue" }]
}
I'd like to perform a select query, which returns all rows with some particular id in the object from departments field.
I managed to create a script that uses a cursor fetching departments field from [Content] column into #content variable and then:
SELECT * FROM OPENJSON(#content) WITH(id int) WHERE id IN (1, 2, 3, 9)
But it returns only departmentid and I need the whole row.
Preferably it should look like that (but code below unfortunately does not work):
SELECT * FROM ITEM I WHERE EXISTS
(SELECT * FROM OPENJSON(I.CONTENT) WITH(id int) WHERE id IN (1, 2, 3, 9))
If I understood you correctly, this could get you what you need:
declare #someId varchar(10) = '1'
declare #json nvarchar(1000) = N'{ "departments": [ { "id": 1, "fieldA": "somevalue" }, { "id": 1, "fieldA": "test" }, { "id": 2, "fieldA": "somevalue" }] }'
select ids.[key], ids.[value] id_val, depts.value content
from openjson(#json, '$.departments') as depts cross apply OPENJSON(depts.value) as ids
where ids.[key] = 'id' and ids.value = #someId
I have added another element to the departments array, with the same Id = 1 just for testing the results.
EDIT:
select ids.[key], ids.[value] id_val, depts.value content
from ITEMS i cross apply openjson(i.Content, '$.departments') as depts cross apply OPENJSON(depts.value) as ids
where ids.[key] = 'id' and ids.value = #id

Resources