I'm trying to import a CSV into a SQL Server database using PowerShell. This is what I'm doing:
$database="myTestDB"
$server="TEST_SERVER"
$table="LOG_TEST"
Import-CSV C:\test\OUTPUT3.csv | ForEach-Object {Invoke-Sqlcmd -Database $database -ServerInstance $server -Query "INSERT INTO $table VALUES ('$($_.col1)',$($_.col2),'$($_.col3)')"}
But I keep getting this error:
Invoke-Sqlcmd : Incorrect syntax near ','.
At line:1 char:57
+ ... ach-Object {Invoke-Sqlcmd -Database $database -ServerInstance $server ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException
+ FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Col2 is an int. I've tried different methods and notations of getting the variables in from the CSV but always similar errors.
Any help would be great. I was following the answer from this question...
How to import data from .csv in SQL Server using PowerShell?
Thanks!
More Information:
I have changed things up to simplify the scenario and so I could give more details here. The table consists of 3 varchar columns. I believe the original errors were due to some issues with the data. The data file I am working with is this saved as test.csv:
col1,col2,col3
a,b,c
1,2,3
d,e,f
4,5,6
g,h,i
7,8,9
My script is:
$database="myTestDB"
$server="Test_Server"
$table="csvLoadTest"
$Query="INSERT INTO $table VALUES ('$($_.col1)','$($_.col2)','$($_.col3)')"
Import-CSV C:\Test_Server\test.csv | ForEach-Object {Invoke-Sqlcmd -Database $database -ServerInstance $server -Query $Query}
The problem I am having now is that the fields are coming in blank. It runs and inserts records but there is no data in the fields.
As a side note... I am aware of the SQL injection risks with this but that is not a real concern for me, in this set up, for a number of reasons. I'm just trying to get it to work at this point. Thanks!