Hi how can I insert a JSON file into a Cell in Database? I don't want to store the File path but want to store the whole Content of the JSON file into the field.
What can I do?
Hi how can I insert a JSON file into a Cell in Database? I don't want to store the File path but want to store the whole Content of the JSON file into the field.
What can I do?
JSON data stored/transferred in as a string. You can store it in a normal NVARCHAR column.
As mentioned, you can store the json file in a NVARCHAR(MAX) column. Here is an example how to load a json file into a NVARCHAR(MAX) variable.
Consider this sample .json file top-posts.json:
[
{
"Id":6107,
"Score":176,
"ViewCount":155988,
"Title":"What are deconvolutional layers?",
"OwnerUserId":8820
},
{
"Id":155,
"Score":164,
"ViewCount":25822,
"Title":"Publicly Available Datasets",
"OwnerUserId":227
}
]
Here is a SQL script to import the json file using OPENROWSET and Bulk import. We also pass in the path to the folder where the json file is. It is put in the same folder as the .sql file script.
Sql-script import_json_file_openrowset.sql:
DECLARE @JSONFILE VARCHAR(MAX);
SELECT @JSONFILE = BulkColumn
FROM OPENROWSET (BULK '$(FullScriptDir)\top-posts.json', SINGLE_CLOB) AS j;
PRINT 'JsonFile contents: ' + @JSONFILE
IF (ISJSON(@JSONFILE)=1) PRINT 'It is valid Json';
The .bat file here passes the current folder as a variable to the sql script
runsqlscript.bat
@set FullScriptDir=%CD%
sqlcmd -S .\SQLEXPRESS -i import_json_file_openrowset.sql
This outputs:
sqlcmd -S .\SQLEXPRESS -i import_json_file_openrowset.sql
JsonFile contents: [
{
"Id":6107,
"Score":176,
"ViewCount":155988,
"Title":"Toreboss: What are deconvolutional layers?",
"OwnerUserId":8820
},
{
"Id":155,
"Score":164,
"ViewCount":25822,
"Title":"Publicly Available Datasets",
"OwnerUserId":227
}
]
It is valid Json
With the variable JSONFILE you can do whatever with it such as inserting it to a column in a new row of a table for example.