如何将JSON对象作为nvarchar插入SQL Server 2016

我想在我的SQL Server 2016表中插入一些
JSON对象.

我的表结构如下:

field           type            nullable   default
name          | nvarchar(max) | true     | Null
age           | nvarchar(max) | true     | Null
homeAddress   | nvarchar(max) | true     | Null
officeAddress | nvarchar(max) | true     | Null

我使用以下查询来插入我的数据:

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)
         );

但是,表中仅填充名称和年龄的值. homeAddress和officeAddress值均为NULL.

我的查询有什么问题?如何将JSON对象作为nvarchar插入?

最佳答案 我承认我在SQL Server 2016中没有使用JSON的经验,但是看看本教程:

https://docs.microsoft.com/en-us/sql/relational-databases/json/solve-common-issues-with-json-in-sql-server

在您的NVARCHAR(最大)列可能是您需要的之后,似乎添加了AS JSON:

INSERT INTO Employee 
    SELECT * 
    FROM OPENJSON(@json)
    WITH (name nvarchar(50), 
          age int, 
          homeAddress nvarchar(max) AS JSON, 
          officeAddress nvarchar(max) AS JSON
         );
点赞