且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 powershell 将 CSV 文件的数据插入 SQL Server db 表

更新时间:2023-01-19 23:08:34

我有两种方法:

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

可以在 这篇博文.