我对SQL不是很熟悉。
我的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
)
我有一个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)."
}
]
如何编写sql来获取此文件并将数据导入到我的Product
表中,而不是手动执行此操作?
我使用的是SQL Server 2016和SSMS。
发布于 2020-04-23 06:01:00
您可以尝试一种方法,它使用OPENROWSET()
(读取文件)和具有显式模式的OPENJSON()
(tp解析输入JSON)。请注意,OPENROWSET()
需要额外的permissions。如果文件包含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'
)
https://stackoverflow.com/questions/61379993
复制