I want to insert a few JSON objects into my SQL Server 2016 table.
My table structure is as follows:
field type nullable default
name | nvarchar(max) | true | Null
age | nvarchar(max) | true | Null
homeAddress | nvarchar(max) | true | Null
officeAddress | nvarchar(max) | true | Null
I am using the following query to insert my data:
DECLARE @json NVARCHAR(MAX) = N'{"name":"John Smith","age":32,"homeAddress":{"addr1":"123rd West Street, Willow Apt","addr2":"#55 Suite","zipCode":12345,"city":"Austin","state":"TX"},"officeAddress":{"addr1":"23rd West Street","addr2":"","zipCode":12345,"city":"Austin","state":"TX"}}';
INSERT INTO Employee
SELECT *
FROM OPENJSON(@json)
WITH (name nvarchar(50),
age int,
homeAddress nvarchar(max),
officeAddress nvarchar(max)
);
However, only the value of name
and age
are populated in the table. Both homeAddress
and officeAddress
values are NULL.
What is wrong with my query? How can I insert a JSON object as nvarchar?
SQL Server and Azure SQL Database have native JSON functions that enable you to parse JSON documents using standard SQL language. You can store JSON documents in SQL Server or SQL Database and query JSON data as in a NoSQL database.
JSON text is stored in VARCHAR or NVARCHAR columns and is indexed as plain text. Any SQL Server feature or component that supports text supports JSON, so there are almost no constraints on interaction between JSON and other SQL Server features.
SELECT BulkColumn FROM OPENROWSET (BULK 'C:\JSON\Books\book. json', SINGLE_CLOB) as j; OPENJSON(BULK) reads the content of the file and returns it in BulkColumn . After loading the contents of the JSON file, you can save the JSON text in a table.
I'll admit I have no experience with JSON stuff in SQL Server 2016, but looking at this tutorial:
https://docs.microsoft.com/en-us/sql/relational-databases/json/solve-common-issues-with-json-in-sql-server
It seems like adding AS JSON
after your NVARCHAR(max)
columns may be what you need:
INSERT INTO Employee
SELECT *
FROM OPENJSON(@json)
WITH (name nvarchar(50),
age int,
homeAddress nvarchar(max) AS JSON,
officeAddress nvarchar(max) AS JSON
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With