如何使用 powershell 将 CSV 文件的数据插入 SQL Server db 表 [英] How to insert data of a CSV file into SQL Server db table using powershell

查看:30
本文介绍了如何使用 powershell 将 CSV 文件的数据插入 SQL Server db 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过从我的本地机器执行 PS 脚本来做到这一点.其中数据库服务器是远程机器.

I want to do this by executing PS Script from my local machine.. where DB server is remote machine.

在 CSV 文件中,我没有指定任何列名.(只有逗号分隔和对齐的 o/p).

And in the CSV file I don't have any column names specified.(only comma separated and aligned o/p).

我不想使用 BULK INSERT

推荐答案

我有两种方法:

BCP.exe

SQL Server 提供命令行实用程序 bcp 来批量导入数据.您可以简单地将 bcp 执行合并到您的 Powershell 脚本或窗口中以加载 csv 数据.示例:

SQL Server provides the command line utility bcp to bulk import data. You could simply incorporate the bcp execution into your Powershell script or window to load the csv data. Example:

$loadfile = "C:datafileloadthis.csv"
bcp pity.dbo.foo in $loadfile -T -c -t","

使用 .NET

您也可以在 Powershell 中使用 .NET 库,但这是一个更棘手的提议.首先,获取 Out-DataTableWrite-DataTable 脚本,由 Chad Miller 编写,这将使您的生活变得更加美好,容易多了.然后您可以执行以下操作:

You could also use the .NET libraries in Powershell, but this is a much trickier proposition. First, get the Out-DataTable and Write-DataTable scripts by Chad Miller, which will make your life much, much easier. Then you could do the following:

$dt = Import-Csv -Path "C:datafileloadthis.csv" | Out-DataTable
Write-DataTable -ServerInstance "localhost" -Database "pity" -TableName "foo" -Data $dt

可以在 这篇博文.

这篇关于如何使用 powershell 将 CSV 文件的数据插入 SQL Server db 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆