0

I am trying to store a value from a selected row from one table into another. My code is as follows.

 string CustomerID = textBox1.Text;


                SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
                con1.Open();
                SqlCommand myCommand = new SqlCommand("Select CustomerID, Name from TableCustomer WHERE (CustomerID like '" + CustomerID+ "')", con1);

                SqlDataReader rdr = myCommand.ExecuteReader();

                    while (rdr.Read())
                    {
                        string Name = rdr["Name"].ToString();

                    }           
                SqlCommand cmd = new SqlCommand(@"insert into finalTable (AccountNumber, CustomerName) VALUES
                (@CustomerID,   @Name )", con);
                cmd.ExecuteNonQuery();

                con1.Close();

My code is not working properly. All is I want to insert Name and ID of customer in Name field of finalTable. What is wrong with this code?

2
Contributors
2
Replies
13
Views
2 Years
Discussion Span
Last Post by blueshiftdani
0

First of all, if you have an CustomerId, you should use equals instead of like. If you use Like you can ending with the wrong customer.
Like this:

WHERE (CustomerID = '" + CustomerID+ "')

Now for the part that doesn't work. On your second query you are not setting the CustomerId nor the Name on your sql string. And you're also using a connection named con that doesn't exists.

You could try like this:

SqlCommand cmd = new SqlCommand(@"insert into finalTable (AccountNumber, CustomerName) VALUES ('" + CustomerId + "', '" + Name + "' )", con1);
cmd.ExecuteNonQuery();

Or you could use a more elegant way with SQL Parameters: http://www.dotnetperls.com/sqlparameter

Edited by AleMonteiro

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.