-1

I have to insert some values in a table while fetching them from another table. Here is my code:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);

SqlCommand myCommand = new SqlCommand("SELECT Name FROM TableName WHERE Id = '" + Id + "'", con);

SqlDataReader rdr = myCommand.ExecuteReader();

if (dr.HasRows)
{
    while (rdr.Read())
    {
        // User exist - get email
        string Name = rdr["Name"].ToString();
    }
}

My question is how to insert the name into another table.

I do not want to use a textbox for this the value must be inserted as a variable into other table. I use following script to insert data . but error message is Id not found. Please let me know if I am missing something

SqlCommand cmd = new SqlCommand(@"insert into finalTable (AccountNumber) VALUES (@string)", con);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bilal Zia
  • 41
  • 1
  • 8

1 Answers1

0

I use following script to insert data . but error message is Id not found.

SqlCommand cmd = new SqlCommand(@"insert into finalTable (AccountNumber) VALUES
        (@string)", con);

You need to specify a value for all columns in the table, unless some columns have default values. Its hard to tell without the exact error message, but it sounds like Id is probably the primary key column and not set to auto increment, so you must supply a value for Id. Since you are inserting, it must be a value not yet used in the table. Depending on your needs, you might want to change finalTable's ID to be auto increment.

On a side note, you are not disposing of things (like your DB connection) that implement IDisposable. The using keyword is your friend here.

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553