Stored Procedure always returning 0

后端 未结 4 1979
温柔的废话
温柔的废话 2021-01-23 02:26

I am trying to get returned value from stored procedure, but it always returning 0.

c# code

cmd = new SqlCommand();
    cmd.CommandType = CommandType.S         


        
4条回答
  •  醉梦人生
    2021-01-23 03:05

    I tried a similar code like yours and it works as expected.
    However, in your code there is a call to ExecuteNonQuery two times.

    When the first call is made the record is inserted as expected, then you add the parameter for the return value and execute again the command. But now the record exists and the stored procedure falls always in the else block thus returning always zero.

    cmd = new SqlCommand();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "AbsentEntry";
    cmd.Parameters.Add("@EmpID", SqlDbType.VarChar).Value = ViewState["empID"].ToString();
    cmd.Parameters.Add("@AttendanceDate", SqlDbType.Date).Value = date.ToString("yyyy-MM-dd");
    SqlParameter returnParameter = cmd.Parameters.Add("@returnval", SqlDbType.Int);
    returnParameter.Direction = ParameterDirection.ReturnValue;
    cmd.Connection = conn;
    conn.Open();
    cmd.ExecuteNonQuery();
    int result = (int)cmd.Parameters["@returnval"].Value;
    return result;
    

提交回复
热议问题