I am trying to get returned value from stored procedure, but it always returning 0.
cmd = new SqlCommand();
cmd.CommandType = CommandType.S
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;
It is because you are using executenonquery.
You should use executescalar to Return a single value.
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()
if count is in your select query u should used executescaler.. like
int result=convert.toint32(cmd.executescalar());
or
int result = (Int32)cmd.ExecuteScalar();