![](/img/trans.png)
[英]How to export SQL Server table data into text file as Insert command?
[英]How to insert JSON file data to SQL Server table using sql command
我對 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。
您可以嘗試一種方法,它使用OPENROWSET()
(讀取文件)和OPENJSON()
與顯式架構(tp 解析輸入 JSON)。 請注意, OPENROWSET()
需要額外的權限。 如果文件包含 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.