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

后端 未结 1 555
情深已故
情深已故 2021-01-26 10:08

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 co

相关标签:
1条回答
  • 2021-01-26 10:49

    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.

    0 讨论(0)
提交回复
热议问题