I have a stored procedure which returns whether a student is locked or not:
RETURN @isLocked
I execute this stored procedure like:
public int IsStudentLocked(string studentName, int lockoutTime)
{
SqlConnection connObj = new SqlConnection();
connObj.ConnectionString = Util.StudentDataInsert();
connObj.Open();
SqlCommand comm = new SqlCommand("uspCheckLockout", connObj);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@Studentname", studentName));
comm.Parameters.Add(new SqlParameter("@LockoutTime", lockoutTime));
comm.ExecuteNonQuery();
connObj.Close();
//How can I return the @isLocked value below?
return ((int)(@isLocked));
}
To use the RETURN
statement in T-SQL (which can ONLY return integer values), you have to add a parameter to retrieve it:
public int IsStudentLocked(string studentName, int lockoutTime)
{
SqlConnection connObj = new SqlConnection();
connObj.ConnectionString = Util.StudentDataInsert();
connObj.Open();
SqlCommand comm = new SqlCommand("uspCheckLockout", connObj);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@Studentname", studentName));
comm.Parameters.Add(new SqlParameter("@LockoutTime", lockoutTime));
var returnParam = new SqlParameter
{
ParameterName = "@return",
Direction = ParameterDirection.ReturnValue
};
comm.Parameters.Add(returnParam);
comm.ExecuteNonQuery();
var isLocked = (int)returnParam.Value;
connObj.Close();
return isLocked;
}
However, this is kinda messy (IMO). Usually what I do in this case is to SELECT
the value that I want as the last statement in my stored procedure. Then I use ExecuteScalar
on the command object to retrieve the value instead of ExecuteNonQuery
.
Proc:
... SQL ...
SELECT @isLocked
Method:
public int IsStudentLocked(string studentName, int lockoutTime)
{
using(SqlConnection connObj = new SqlConnection())
{
connObj.ConnectionString = Util.StudentDataInsert();
connObj.Open();
SqlCommand comm = new SqlCommand("uspCheckLockout", connObj);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@Studentname", studentName));
comm.Parameters.Add(new SqlParameter("@LockoutTime", lockoutTime));
return (int)comm.ExecuteScalar();
}
}
You should call ExecuteScalar instead of ExecuteNonQuery and replace RETURN with SELECT in your stored proc.
By the way, you should wrap your connection with using
block, so it will be properly disposed even in case when some exception occured before Close().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With