我想在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
的值。 homeAddress
和officeAddress
值均为NULL。
我的查询有什么问题?如何将JSON对象作为nvarchar插入?
答案 0 :(得分:1)
我承认我在SQL Server 2016中没有使用JSON的经验,但是看看本教程:
在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
);