Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert JSON object to SQL Server 2016 as nvarchar

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?

like image 1000
KnightCavalry Avatar asked Sep 20 '17 13:09

KnightCavalry


People also ask

Can we store JSON data in SQL Server?

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.

Is there a JSON data type in SQL Server?

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.

How do I import a JSON file into a SQL Server table?

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.


1 Answers

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
         );
like image 153
Eric Petroelje Avatar answered Sep 29 '22 21:09

Eric Petroelje