I had posted a questing back in jan. about updating a sql database from a csv file, and received some great suggestions. I tried adding to that question but it wouldn’t let me( too old perhaps?).
I was able to add rows to the database with the code I created, but it appeared to add duplicates. so I have tried the following code and I am getting errors… such as "incorrect syntax near the key word ‘from’ " and "Exception calling “ExecuteNonQuery” with “0” argument(s): “Conversion failed when converting the varchar value ‘luis’ to data type int.”
$userlist = Import-CSV C:\scripts\HS-Student-with-pass.csv $database = 'HSStudents' $server = 'HP600-WIN8-MG\SQLEXPRESS' $table = 'dbo.StudentInfo' $SQLServer = "HP600-WIN8-MG\sqlexpress" $SQLDBName = "HSStudents" $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True" $SqlConnection.Open() Foreach($user in $userlist){ $col1 = $user.stuid $col2 = $user.lastname $col3 = $user.firstname $col4 = $user.gradelevel $col5 = $user.status $col6 = $user.homeroom $col7 = $user.hrteacher $col8 = $user.newpassword $dbwrite = $SqlConnection.CreateCommand() $dbwrite.CommandText = "IF NOT EXISTS (select from $table where stuid = $col1 ) INSERT INTO $table (stuid, lastname,firstname,gradelevel,status,homeroom,hrteacher,newpassword) VALUES ('$col1','$col2','$col3','$col4','$col5','$col6','$col7','$col8')" $dbwrite.ExecuteNonQuery() # | out-null } $SqlConnection.Close()
Im trying to add an “if not exists… then insert new data row”. the “stuid” column is the unique column.
any suggestions appreciated as to what im doing wrong… ive been googling for days and this is the best point ive gotten too as the best way to update an existing sql database with info that has been received via a csv file.