How to import data from .csv in SQL Server using PowerShell?

前端 未结 1 839
执念已碎
执念已碎 2020-12-06 14:40

I have the following scenario: Iam using PowerShell and have to import data from a .csv file into a already created table on a SQL Server Database. So i dont need the header

相关标签:
1条回答
  • 2020-12-06 15:07

    I wrote a blog post about using SQL with PowerShell, so you can read more about it here.

    We can do this easily if you have the SQL-PS module available. Simply provide values for your database name, server name, and table, then run the following:

    $database = 'foxdeploy'
    $server = '.'
    $table = 'dbo.powershell_test'
    
    Import-CSV .\yourcsv.csv | ForEach-Object {Invoke-Sqlcmd `
      -Database $database -ServerInstance $server `
      -Query "insert into $table VALUES ('$($_.Column1)','$($_.Column2)')"
      }
    

    To be clear, replace Column1, Column2 with the names of the columns in your CSV.

    Be sure that your CSV has the values in the same format as your SQL DB though, or you can run into errors.

    When this is run, you will not see any output to the console. I would recommend querying afterwards to be certain that your values are accepted.

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