简体   繁体   English

如何使用 sql 命令将 JSON 文件数据插入到 SQL Server 表中

[英]How to insert JSON file data to SQL Server table using sql command

I am not so familiar with SQL.我对 SQL 不太熟悉。

I have a table in my SQL Server database called Product我的 SQL Server 数据库中有一个名为Product

CREATE TABLE [dbo].[Product] (
[Age]          INT           NULL,
[Name]         NVARCHAR (50) NULL,
[Id]           NVARCHAR (50) NULL,
[Price]        DECIMAL (18)  NULL,
[ImageUrl]     NVARCHAR (50) NULL,
[Snippet]      NVARCHAR (50) NULL
)

I have a JSON file (which locates in D:\\demo\\myjson.json ) where stores all my product info like:我有一个 JSON 文件(位于D:\\demo\\myjson.json ),其中存储了我的所有产品信息,例如:

[
  {
      "Age": 0, 
      "Id": "motorola-xoom-with-wi-fi", 
      "ImageUrl": "static/imgs/phones/motorola-xoom-with-wi-fi.0.jpg", 
      "Name": "Motorola XOOM\u2122 with Wi-Fi", 
      "Price":5000,
      "Snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb)."
  }, 
  {
      "Age": 1, 
      "Id": "motorola-xoom", 
      "ImageUrl": "static/imgs/phones/motorola-xoom.0.jpg", 
      "Name": "MOTOROLA XOOM\u2122", 
      "Price":5000,
      "Snippet": "The Next, Next Generation\n\nExperience the future with MOTOROLA XOOM, the world's first tablet powered by Android 3.0 (Honeycomb)."
  }

]

How can I write sql to get this file and import data into my Product table instead of manually doing this?如何编写 sql 来获取此文件并将数据导入到我的Product表中,而不是手动执行此操作?

I am using SQL Server 2016 and SSMS.我正在使用 SQL Server 2016 和 SSMS。

You may try an approach, which uses OPENROWSET() (to read the file) and OPENJSON() with explicit schema (tp parse the input JSON).您可以尝试一种方法,它使用OPENROWSET() (读取文件)和OPENJSON()与显式架构(tp 解析输入 JSON)。 Note, that OPENROWSET() needs additional permissions .请注意, OPENROWSET()需要额外的权限 If the file contains unicode (widechar) input you should use SINGLE_NCLOB .如果文件包含 unicode (widechar) 输入,则应使用SINGLE_NCLOB

DECLARE @json nvarchar(max)

SELECT @json = BulkColumn
FROM OPENROWSET (BULK 'D:\demo\myjson.json', SINGLE_CLOB) as j

INSERT INTO [Product] ([Age], [Name], [Id], [Price], [ImageUrl], [Snippet])
SELECT [Age], [Name], [Id], [Price], [ImageUrl], [Snippet]
FROM OPENJSON(@json) WITH (
   Age int '$.Age',
   Name nvarchar(50) '$.Name',
   Id nvarchar(50) '$.Id',
   ImageUrl nvarchar(50) '$.ImageUrl',
   Price decimal(18) '$.Price',
   Snippet nvarchar(50) '$.Snippet'
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM