如何将 JSON 对象作为 nvarchar 插入到 SQL Server 2016
How to insert JSON object to SQL Server 2016 as nvarchar
我想在我的 SQL Server 2016 table 中插入一些 JSON 对象。
我的table结构如下:
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)
);
但是,table 中只填充了 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 Server 2016 table 中插入一些 JSON 对象。
我的table结构如下:
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)
);
但是,table 中只填充了 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
);