简体   繁体   中英

How to insert data of a CSV file into SQL Server db table using powershell

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

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

I don't want to use BULK INSERT

There are two ways I would approach this:

BCP.exe

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:\datafile\loadthis.csv"
bcp pity.dbo.foo in $loadfile -T -c -t","

Using .NET

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:\datafile\loadthis.csv" | Out-DataTable
Write-DataTable -ServerInstance "localhost" -Database "pity" -TableName "foo" -Data $dt

These and other solutions can be found in detail in this blog post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM