The variable name '@' has already been declared. Variable names must be unique within a query batch or stored procedure. in c#

前端 未结 5 1722

The variable name \'@LockState\' has already been declared. Variable names must be unique within a query batch or stored procedure.

Wh

5条回答
  •  生来不讨喜
    2020-12-17 19:54

    You are adding multiple times the same parameters in every iteration of loop.

    Add rwd.command.Parameters.Clear() after each loop iteration:

    for (long counter = from; counter <= to; counter++)
    {
        rwd.command.Parameters.Clear();
    
        string upd = "update card set LockState=@lockstate, card_descr=@card_descr where [cardNumber] = N'{0}'";
        rwd.command.CommandText = upd;
        rwd.command.Parameters.Add(new SqlParameter("@LockState",
        SqlDbType.NVarChar)).Value =1;
        rwd.command.Parameters.Add(new SqlParameter("@card_descr",
        SqlDbType.NVarChar)).Value = txt_desc2.Text;
        rwd.connection.Open();
        rwd.command.ExecuteScalar();
        rwd.connection.Close();
    }
    

    or add parameter before loop:

    rwd.command.Parameters.Add(new SqlParameter("@LockState", SqlDbType.NVarChar));
    rwd.command.Parameters.Add(new SqlParameter("@card_descr", SqlDbType.NVarChar));
    

    and then in loop:

    for (long counter = from; counter <= to; counter++)
    {
        string upd = "update card set LockState=@lockstate,
        card_descr=@card_descr where [cardNumber] = N'{0}'";
        rwd.command.CommandText = upd;
    
        rwd.command.Parameters["@LockState"].Value =1;
        rwd.command.Parameters["@card_descr"].Value = txt_desc2.Text;
    
        rwd.connection.Open();
        rwd.command.ExecuteScalar();
        rwd.connection.Close();
    }
    

提交回复
热议问题