Insert data row wise in a SQL Table from a CSV using PowerShell

孤街浪徒 提交于 2019-12-01 07:48:48

问题


So I have this particular scenario where I need to insert data from multiple CSV files into multiple SQL tables. I have come across this SO link, which inserts data on a row by row basis. Below is the code-snippet from the link -

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

The problem which I am facing is, I have multiple CSVs with the different number of columns in them. So the option of hard-coding the code-snippet VALUES('$($_.Column1)','$($_.Column2)') doesn't exist.

Further, there are tables which contain more than 100 columns. So, writing VALUES('$($_.Column1)','$($_.Column2)')... so on upto '$($_.Column100)' is also not feasible.

What I have done for the same is stored the column names from the CSVs into a PowerShell array like this -

$File = "C:\Users\vivek.singh\Desktop\ALL_EMAILS.csv"
$csvColumnNames = (Get-Content $File | Select-Object -First 1).Split(",")

Now $csvColumnNames, has all the column names for ALL_EMAILS table. I am trying to fit it in the solution -

Import-CSV .\yourcsv.csv | ForEach-Object {Invoke-Sqlcmd `
  -Database $database -ServerInstance $server `
  -Query "insert into $table VALUES ('$($csvColumnNames[0])','$($csvColumnNames[1])',..'$($csvColumnNames[$csvColumnNames.Length])')"
  }

But it doesn't seem to work. I have been struggling with this for quite some time now and running out of ideas. A fresh pair of eyes will be greatly appreciated.


回答1:


Try this

Import-CSV .\yourcsv.csv | ForEach-Object {
    $AllValues = "'"+($_.Psobject.Properties.Value -join "','")+"'"
    Invoke-Sqlcmd -Database $database -ServerInstance $server `
    -Query "insert into $table VALUES ($AllValues)"
}

It uses the -join operator to concatenate all values of the current row (with a leading and trailing ' to build the $AllValuesvariable which then can be inserted into the sql command.

It's up to you to check if Csv headers match the sql column names.

To get column names once Import-Csv-ed you can use

$CSV.Psobject.Properties.Name


来源:https://stackoverflow.com/questions/50252209/insert-data-row-wise-in-a-sql-table-from-a-csv-using-powershell

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