Stored Procedure always returning 0

后端 未结 4 1980
温柔的废话
温柔的废话 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;
    
    0 讨论(0)
  • 2021-01-23 03:13

    It is because you are using executenonquery.

    You should use executescalar to Return a single value.

    0 讨论(0)
  • 2021-01-23 03:16

    You do not have an out parameter in your stored procedure, and you are using ExecuteNonQuery -- basically, client side you aren't giving the reurn value anywhere to go. In C# terms it's as if you called a function, but didn't make it part of an assignment. x=getX(); vs getX();

    You can fix this by either changing the stored procedure sothat it has an output parameter

    ALTER PROCEDURE [dbo].[AbsentEntry] 
        @EmpID varchar(10), 
        @AttendanceDate Date,
        @returnval     int OUTPUT
    
    AS BEGIN
    
        IF (SELECT COUNT(*) FROM tblEmpAttendance 
            WHERE EmpID = @EmpID AND AttendanceDate=@AttendanceDate) = 0
        BEGIN
            insert into tblEmpAttendance (EmpID, AttendanceDate, IsInOut,
            SessionCount, IsPresent) values ( @EmpID,@AttendanceDate,'OUT',0,'A')
            set @returnval=1
        END
    ELSE
        BEGIN
           set @returnval=0 
        END
    END
    

    Or, more simply, by using ExecuteScalar and assign the result to a variable.

    int result = (int) cmd.ExecuteScalar()
    
    0 讨论(0)
  • 2021-01-23 03:17

    if count is in your select query u should used executescaler.. like

    int result=convert.toint32(cmd.executescalar());
    

    or

    int result = (Int32)cmd.ExecuteScalar();
    
    0 讨论(0)
提交回复
热议问题