小编典典

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

sql

我想在我的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)
         );

但是,表中仅填充name和的值age。这两个homeAddressofficeAddress值是NULL。

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


阅读 199

收藏
2021-04-07

共1个答案

小编典典

我承认我对SQL Server 2016中的JSON内容没有任何经验,但是请看一下本教程:

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

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

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