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

試著忘記壹切 提交于 2019-12-20 06:35:05

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/22405575/how-to-insert-data-of-a-csv-file-into-sql-server-db-table-using-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!