我想将一些 JSON 对象插入到我的 SQL Server 2016 表中。
我的表结构如下:
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
的值。 homeAddress
和 officeAddress
值均为 NULL。
我的查询有什么问题?如何插入 JSON 对象作为 nvarchar?
最佳答案
我承认我对 SQL Server 2016 中的 JSON 内容没有任何经验,但看看本教程:
似乎在您的 NVARCHAR(max)
列之后添加 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
);
关于sql - 如何将 JSON 对象作为 nvarchar 插入到 SQL Server 2016,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46323946/