arrays - 如何在 SQL Server 的一个字段中插入所有数组元素?
问题描述
我有一个名为“RecordIds”的列。我正在将数据从 json 导入到 sql server 。我有这个 json 文件。但是当我在表中插入所有内容但在最后三个字段中时,我在数据库表中没有任何值。我怎么解决这个问题 ?
{
"Id": 1,
"ImageName": "person1",
"PersonName": "C1-C4:stretch",
"GroupId": 1,
"Text": "Sam has complete C4 tetraplegia. He sits in his power wheelchair all day and is unable to move his arms.<br/><br/>The aim of Sam`s programme is to prevent contracture.<br/><br/>This programme is suitable for people with C1-C4 tetraplegia.",
"RecordIds": [511, 517, 569, 571, 688, 1037],
"DropdownIds": [1, 56, 58],
"TextTitleIds": [3, 5, 7]
}
这是我的查询
declare @details varchar(max)
select @details =
BulkColumn
from openrowset(BULK'D:\JSON\mmh\examples.json', single_blob) json
if(ISJSON(@details) = 1)
begin
print 'Valid Json'
insert into [dbo].[Examples]
select * from
openjson(@details, '$.example')
with(
id smallint '$.Id',
[ImageName] varchar(50) '$.ImageName',
[PersonName] varchar(50) '$.PersonName',
[GroupId] smallint '$.GroupId',
[Text] varchar(50) '$.Text',
[RecordIds] varchar(50) '$.RecordIds',
[DropdownIds] varchar(50) '$.DropdownIds',
[TextTitleIds] varchar(50) '$.TextTitleIds'
)
end
else
begin
print 'invalid Json'
end
我得到了这个输出
RecordIds DropdownIds TextTitleIds
NULL NULL NULL
解决方案
您需要使用AS JSON,例如
declare @json nvarchar(max) =
'{
"example":
{
"Id": 1,
"ImageName": "person1",
"PersonName": "C1-C4:stretch",
"GroupId": 1,
"Text": "Sam has complete C4 tetraplegia. He sits in his power wheelchair all day and is unable to move his arms.<br/><br/>The aim of Sam`s programme is to prevent contracture.<br/><br/>This programme is suitable for people with C1-C4 tetraplegia.",
"RecordIds": [511, 517, 569, 571, 688, 1037],
"DropdownIds": [1, 56, 58],
"TextTitleIds": [3, 5, 7]
}
}'
select * from
openjson(@json, '$.example')
with(
id smallint '$.Id',
[ImageName] varchar(50) '$.ImageName',
[PersonName] varchar(50) '$.PersonName',
[GroupId] smallint '$.GroupId',
[Text] varchar(50) '$.Text',
[RecordIds] nvarchar(MAX) '$.RecordIds' as json,
[DropdownIds] nvarchar(MAX) '$.DropdownIds' as json,
[TextTitleIds] nvarchar(MAX) '$.TextTitleIds' as json
)
推荐阅读
- swift - 使用 IOKit 和 Swift 进行简单的键重映射
- wordpress - Web 开发人员学习 WordPress 的最小学习曲线
- plotly - 这个 Plotly_Express 代码的 Plotly Graph_Objects 等价物是什么?
- python - 如何将文件拖放到从 Qt Designer 创建的 QListWidget 中?
- json - 使用 Python 或 jq 将值附加到 ndjson 文件中每隔一行的开头和结尾
- embedded - 如何在 stm32 微控制器上设置中断寄存器?
- reactjs - 如何在测试组件时为响应状态分配值?
- python - 如何在列上迭代 re.search 函数
- awk - 使用 grep 或 awk 查找 txt 和 csv 文件之间的匹配行
- c# - Avalonia 中的 GetTemplateChild / TemplatePart?