Save values from select query then use them in update query SQL Server CE

469 views Asked by At

I have a Winforms application with a SQL Server CE 3.5 database. I want to do an UPDATE query and for this I need a SELECT query.

Here's what I wrote:

string command1 = "SELECT Column1, Column2, Column3 FROM Table1";
string command2 = "UPDATE Table2 SET Column2 = @var2, Column3 = @var3 WHERE Column1 = @var1";

using (SqlCeCommand cmd1=new SqlCeCommand(command1, connection))
{
     SqlCeDataReader reader;
     reader = cmd1.ExecuteReader();

     while (reader.Read())
     {
         int var1 = (int)reader[0];
         int var2 = (int)reader[1];
         string var3 = (string)reader[2];

         SqlCeCommand cmd2= new SqlCeCommand (command2, connection);
         cmd2.ExecuteReader();
     }
}

I get an error

A parameter is missing. Parameter ordinal=3

2

There are 2 answers

0
marc_s On BEST ANSWER

You have three parameters in your second command (command2) - but you never define those parameters, nor do you set any values for them to use!

Try this code:

string command1 = "SELECT Column1, Column2, Column3 FROM Table1";
string command2 = "UPDATE Table2 SET Column2 = @var2, Column3 = @var3 WHERE Column1 = @var1";

using (SqlCeCommand cmd1 = new SqlCeCommand(command1, connection))
{
     // define your "cmd2" here, once, before the loop
     SqlCeCommand cmd2 = new SqlCeCommand (command2, connection);

     // define the parameters
     cmd2.Parameters.Add("@var1", SqlDbType.Int);
     cmd2.Parameters.Add("@var2", SqlDbType.Int);
     cmd2.Parameters.Add("@var3", SqlDbType.VarChar, 100);

     SqlCeDataReader reader = cmd1.ExecuteReader();

     while (reader.Read())
     {
         int var1 = (int)reader[0];
         int var2 = (int)reader[1];
         string var3 = (string)reader[2];

         // set the *values* of the parameters
         cmd2.Parameters["@var1"].Value = var1;
         cmd2.Parameters["@var2"].Value = var2;
         cmd2.Parameters["@var3"].Value = var3;

         cmd2.ExecuteNonQuery();
     }
}
0
Ted On

You are not using the var1, var2 and var3 variables. I guess they represent the second query parameters so you should use them like this :

SqlCeParameter param = new SqlCeParameter("@var1", SqlDbType.Int); command.Parameters.Add(param);

See the official documentation here : https://msdn.microsoft.com/fr-fr/library/system.data.sqlserverce.sqlcecommand.parameters(v=vs.100).aspx