执行两个不同的命令,但只影响一个表

时间:2012-08-04 16:53:36

标签: c# sql-server

我有一张表materials,另一张表stock_refund。我在单击按钮上执行这两个命令同时更新两个表,但两个记录都进入同一个表。以下是我的代码:

SqlConnection con = new SqlConnection(@"Data Source=ANONYMOUS\SQLSERVER;Initial Catalog=IndoStar;Integrated Security=SSPI;");
con.Open();
SqlCommand cmd = new SqlCommand("Insert into stock_refund values('"+refund_stockname.Text + "','"+refund_sitename.Text + "','"+refund_day.Text + refund_month.Text + refund_year.Text + "','"+refund_quantity.Text + "','"+ refund_unit.Text+"')",con);
SqlCommand cmd1 = new SqlCommand("Insert into materials values('" + refund_stockname.Text + "','" + refund_day.Text + refund_month.Text + refund_year.Text + "','" + refund_quantity.Text + "','" + refund_unit.Text + "', 'refund','"+ refund_sitename.Text +"')", con);
int i = cmd.ExecuteNonQuery();
int j = cmd.ExecuteNonQuery();
if ((i > 0)&& (j>0))
{
    MessageBox.Show("Stock refunded successfully","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
}

1 个答案:

答案 0 :(得分:3)

这里似乎有一个错字:

int i = cmd.ExecuteNonQuery();
int j = cmd.ExecuteNonQuery();

应该是

int i = cmd.ExecuteNonQuery();
int j = cmd1.ExecuteNonQuery();

您正在执行第一个命令两次。