I am using PowerShell to run a SQL query. I then want to update another table based on information pulled from the query. I have tested my SQL query and update statements directly in the SQL Server Management Studio so I know that they work. The results of those tests show that there are over 800 records that should be updated. However, when I run the same query and update from within PowerShell, it only updates one record. I have mostly copied this script from another much larger script that was written in a similar format. But it appears that I am missing a ForEach loop (or something similar) but cannot figure out where to place it or how. Here is my script:
# Set the database connection strings
$Conn02 = new-object System.Data.SqlClient.SqlConnection "SERVER_INFORMATION"
$mySQL02 = New-Object System.Data.SqlClient.SqlCommand
$mySQL02.Connection = $Conn02
$Conn03 = new-object System.Data.SqlClient.SqlConnection "SERVER_INFORMATION"
$mySQL03 = New-Object System.Data.SqlClient.SqlCommand
$mySQL03.Connection = $Conn03
#Connect to the database to perform the query
$Conn02.Open()
$mySQL02.CommandText = "SELECT IDNUM, FNAME, LNAME
FROM TABLE1
WHERE STATUS = 'C'"
$SQL02 = $mySQL02.ExecuteReader()
WHILE($SQL02.Read()){
$NEWID = $SQL02['ID_NUM']
$FNAME1 = $SQL02['FNAME']
$LNAME1 = $SQL02['LNAME']
}
#Run the update
$Conn03.Open()
$mySQL03.CommandText =
"INSERT INTO TABLE2 (user_id,firstname,lastname)
VALUES ('$NEWIDme','$FNAME1','$LNAME1')"
Thank you for your time
INSERT, so obviously you will only ever end up inserting a single row. The loop that reads the result just ends up discarding everything but the very last row. You should move theINSERTinto the read loop (but still use a separate connection, since the reader is occupying the other one). Make sure to call.Close()on your connections when all is said and done (readers and commands technically need to be disposed as well, but closing the connection takes care of that).O'Toolewill not work correctly, for example, nor willNULLvalues). Use properly parameterized statements; it's a bit more work but it pays off. A snippet for your perusal.