sql-server - 在 SQL 表中存储 json 数组
问题描述
我有两个表:用户和电话。桌面电话具有对桌面用户的引用。这允许每个用户有多个电话号码。
我正在以 json 格式将信息发送到 SQL 服务器,但我正在努力存储电话号码。这是我到目前为止所拥有的:
CREATE TABLE [dbo].[user](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[phone](
[id] [int] IDENTITY(1,1) NOT NULL,
[userId] [int] NOT NULL,
[type] [varchar](12) NOT NULL,
[phone] [varchar](12) NOT NULL
) ON [PRIMARY]
GO
DECLARE @jsonVariable NVARCHAR(MAX)
SET @jsonVariable = N'{
"name":"Joe Smith",
"phones":[
{
"phone":"+1 123 123-4567",
"type":"business"
},
{
"phone":"+1 987 987-6543",
"type":"mobile"
}
]
}'
DECLARE @userId int
DECLARE @userName varchar(max) = (SELECT userName FROM OPENJSON (@jsonVariable) WITH (userName varchar(max) N'$.name'))
INSERT INTO [dbo].[user] ([name]) VALUES (@userName)
SET @userId = @@IDENTITY
现在的问题是:是否有类似“forEach”的程序来存储所有电话号码?
解决方案
您可以使用 OPENJSON 从您的 json 中的电话数组中获取所有记录。
试试这个作为你现有代码的一部分:
INSERT INTO [dbo].[phone] (
[userId]
, [type]
, [phone]
)
SELECT @userId
, [c].[type]
, [c].[phone]
FROM [dbo].[user] [a]
INNER JOIN OPENJSON(@jsonVariable)
WITH (
[userName] VARCHAR(MAX) '$.name'
, [phones] NVARCHAR(MAX) AS JSON --bring your phones array back out.
) AS [b]
ON [b].[userName] = [a].[name]
CROSS APPLY OPENJSON([b].[phones]) --Cross apply to get all records. This will return all the records in phones for the specific user you have inserted in dbo.[user]
WITH (
[phone] NVARCHAR(12) '$.phone'
, [type] NVARCHAR(12) '$.type'
) [c];
推荐阅读
- javascript - 通过 Ajax - MVC 将切换开关值插入 DB
- android - 了解如何在 android/Iphone 之间为 offer/answer (webrtc) 生成正确的 sdp
- vue-router - 如何将 vue-router 链接添加为 ag-grid-vue 列?
- cluster-analysis - 如何计算两个树状图中两个个体之间或两种聚类方法之间的共同相似性?
- jenkins - Jenkins 上安装后脚本的 npm install PATH
- typescript - 使用 Typescript 3 构建到 dist/ 文件夹时保持 src/ 文件夹结构
- android - 在 android studio 中添加 5 列表格行布局
- javascript - 除非字符串中有括号,否则前瞻不匹配
- javascript - 从生成的聊天窗口中抓取带有时间戳的文本数据
- postgresql - 我们如何配置 postgresql 9.2 以关闭比某个时间间隔更早的连接?