将值从存储过程返回到方法
我有一个存储过程,它返回学生是否被锁定:
RETURN @isLocked
我执行这个存储过程,如:
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)); }
要在T-SQL中使用RETURN
语句(只能返回整数值),您必须添加一个参数来检索它:
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; }
但是,这有点混乱(IMO)。 通常我在这种情况下做的是SELECT
我想要的值作为我的存储过程中的最后一个语句。 然后我在命令对象上使用ExecuteScalar
来检索值而不是ExecuteNonQuery
。
PROC:
... SQL ... SELECT @isLocked
方法:
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(); } }
您应该调用ExecuteScalar而不是ExecuteNonQuery,并在存储过程中用SELECT替换RETURN。
顺便说一下,你应该using
block包装你的连接,所以即使遇到Close()之前发生了一些exception,它也会被妥善处理。
如果@IsLocked存储过程中的输出参数
System.Data.SqlClient.SqlParameter paramterIsLockedOut = command1.Parameters.Add("@MyParameter", SqlDbType.SmallInt); paramterIsLockedOut.Direction = ParameterDirection.Output; command1.ExecuteNonQuery(); int newValue = (int)paramterIsLockedOut.Value;