When attempting to execute SQL code, you may encounter the error "The variable name '@LockState' has already been declared. Variable names must be unique within a query batch or stored procedure." This issue arises due to the inclusion of multiple instances of the same parameter in a loop.
To resolve this error, you can either clear the parameters after each loop iteration or add the parameters before the loop.
for (long counter = from; counter <= to; counter++) { // Clear parameters before adding new ones rwd.command.Parameters.Clear(); string upd = "update card set LockState=@lockstate, card_descr=@card_descr where [cardNumber] = N'{0}'"; rwd.command.CommandText = upd; rwd.command.Parameters.Add(new SqlParameter("@LockState", SqlDbType.NVarChar)).Value = 1; rwd.command.Parameters.Add(new SqlParameter("@card_descr", SqlDbType.NVarChar)).Value = txt_desc2.Text; rwd.connection.Open(); rwd.command.ExecuteScalar(); rwd.connection.Close(); }
rwd.command.Parameters.Add(new SqlParameter("@LockState", SqlDbType.NVarChar)); rwd.command.Parameters.Add(new SqlParameter("@card_descr", SqlDbType.NVarChar)); for (long counter = from; counter <= to; counter++) { string upd = "update card set LockState=@lockstate, card_descr=@card_descr where [cardNumber] = N'{0}'"; rwd.command.CommandText = upd; // Assign values to parameters within the loop rwd.command.Parameters["@LockState"].Value = 1; rwd.command.Parameters["@card_descr"].Value = txt_desc2.Text; rwd.connection.Open(); rwd.command.ExecuteScalar(); rwd.connection.Close(); }
By implementing either of these solutions, you can effectively resolve the parameter redundancy issue and ensure the successful execution of your SQL code.
The above is the detailed content of How to Resolve the 'The variable name '@' Has Already Been Declared' SQL Error?. For more information, please follow other related articles on the PHP Chinese website!