我试图一次将一些数据插入到 2 个表中,但我的代码遇到的问题是......我一次只能插入一个表。如果我注释掉第一个插入语句,那么第二个插入将起作用,反之亦然。
这是我的代码
SqlCommand cmd = new SqlCommand("select Name from MainTable where Name= '" + Name+ "' ", sqlcon);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
lblmsg.Text = "We are already have this Name" + Name;
}
else
{
dr.Close();
sqlcmd.CommandText = "INSERT INTO Table1(Name, Address) VALUES(@Name, @Address)";
sqlcmd.CommandText = "INSERT INTO Table2(Company, Address2) VALUES(@Company, @Address2)";
sqlcmd.Parameters.Clear();
sqlcmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = Name;
sqlcmd.Parameters.Add("@Address", SqlDbType.VarChar).Value = Address;
sqlcmd.Parameters.Add("@Company", SqlDbType.VarChar).Value = Company
sqlcmd.Parameters.Add("@Address2", SqlDbType.VarChar).Value = Address2;
sqlcmd.Connection = sqlcon;
sqlcmd.ExecuteNonQuery();
DV_NameAdd.ChangeMode(DetailsViewMode.ReadOnly);
sqlcon.Close();
}
sqlcon.Close();