Stored Procedure always returning 0

后端 未结 4 2057
温柔的废话
温柔的废话 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: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()
    

提交回复
热议问题