在SQL表中存储JSON数组

时间:2019-07-01 19:26:33

标签: sql-server

我有两个表:user和phone。台式电话具有对台式用户的引用。这样可以为每个用户提供几个电话号码。

我正在以json格式将信息发送到SQL Server,但是我正在努力存储电话号码。这是我到目前为止的内容:

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”例程之类的东西来存储所有电话号码?

1 个答案:

答案 0 :(得分:0)

您可以使用OPENJSON从json中的phones数组中获取所有记录。

尝试将其作为现有代码的一部分:

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];