如何从在线 CSV 插入 SQL Server 数据库数据?

2021-09-10 00:00:00 tsql sql-server

我需要每天从在线可用的 csv 中执行数据加载,例如http://www.supplier.com/products.csv一旦我将 csv 转储到 sql 表中,我就可以进行处理,然后我需要更新/插入等.问题是我不知道如何自动加载数据.

I need to perform a dataload every day from a csv available online e.g. http://www.supplier.com/products.csv Once I've dumped the csv into a sql table I can do the processing I then need to update / insert etc. The problem is that I don't know how to automate the dataload.

我希望我可以使用计划在每天 06:00 运行的 SQL 作业/任务,给它一个 uri,然后它可以访问 csv 中的数据...

I was hoping I could use a SQL job / task, scheduled to run each day at 06:00, give it a uri and that it could then access the data in the csv...

我该怎么做?

推荐答案

您可以安排 SQL 代理作业在本地下载文件并使用 批量插入:

You can schedule a SQL Agent job to download the file locally and use BULK INSERT:

CREATE TABLE StagingCSV
(
   col1 VARCHAR(60),
   col2 VARCHAR(60),
   col3 VARCHAR(60),
   col4 VARCHAR(60),
    -- ...
)
GO

(错误行将被忽略)

BULK
INSERT StagingCSV
FROM 'c:\mycsvfile.txt'
WITH
(
   FIELDTERMINATOR = ',',
   ROWTERMINATOR = '\n'
)
GO

其他方法:

关于批量导入和批量导出操作

使用 BULK INSERT 或 OPENROWSET 导入批量数据

您可以使用 Powershell 下载文件:

You can use Powershell to download a file:

$clnt = new-object System.Net.WebClient
$url = "http://www.supplier.com/products.csv "
$file = "c:\temp\Mycsv.txt"
$clnt.DownloadFile($url, $file)

相关文章