首页 > 解决方案 > 运行多个 sql 命令

问题描述

我在执行多个 sql 命令时遇到问题。我需要多次更新数据。第一个 sql 查询考虑了这两种情况 if,else; 但随后第二个和第三个 sqlcommand 将相应地出现在 if 或 else 中。问题是只有一个 sqlcommand 正常工作,即位于循环内的那些。

public void Button_Submit_Onclick(object sender, EventArgs e)
    {

        for (int i = 0; i < GridView2.Rows.Count; i++)
        {
            con.ConnectionString = ConfigurationManager.ConnectionStrings["TestDeductionsConnectionString2"].ToString();
            int recordid = Convert.ToInt32(GridView2.DataKeys[i].Values[0]);

            CheckBox cbox = (CheckBox)GridView2.Rows[i].FindControl("CheckBox1");
            bool private1 = Convert.ToBoolean(cbox.Checked); 

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "Update DetailCosts set private='" + private1 + "' where recordid=" + recordid;

            con.Open();
            if (private1==true)
            {
                cmd.CommandText = "Update DetailCosts set privateCost=Costs where recordid=" + recordid;
                cmd.Parameters.AddWithValue("@private1", SqlDbType.Bit).Value = private1;
                cmd.Parameters.AddWithValue("@recordid", SqlDbType.Int).Value = recordid.ToString();

            }
            else
            {
                cmd.CommandText = "Update DetailCosts set privateCost=0 where recordid=" + recordid;
                cmd.Parameters.AddWithValue("@recordid", SqlDbType.Int).Value = recordid.ToString();
                cmd.Parameters.Add("@private1", SqlDbType.Bit).Value = private1;

            }
            cmd.ExecuteNonQuery();
            con.Close();
        }


    }

标签: c#sqlasp.netvisual-studiosqlcommand

解决方案


You need to execute every command you want executed so you should add a

cmd.ExecuteNonQuery();

after your first query to have it also be executed.

If you want both to be executed and not if one fails you should implement transactions and wrap both queries in a transaction.


推荐阅读