当前位置: 首页 > 编程语言 > C#

从存储过程返回值到方法分享

时间:2023-04-11 10:49:40 C#

从存储过程返回值到方法我有一个存储过程返回学生是否被锁定:RETURN@isLockedstudentName,intlockoutTime){SqlConnectionconnObj=newSqlConnection();connObj.ConnectionString=Util.StudentDataInsert();connObj.Open();SqlCommandcomm=newSqlCommand("uspCheckLockout",connObj);comm.CommandType=CommandType.StoredProcedure;comm.Parameters.Add(newSqlParameter("@Studentname",studentName));comm.Parameters.Add(newSqlParameter("@LockoutTime",lockoutTime));comm.ExecuteNonQuery();connObj.Close();//如何返回下面的@isLocked值?返回((int)(@isLocked));}要在T-SQL中使用RETURN语句(它只能返回整数值),您必须添加一个参数来检索它:publicintIsStudentLocked(stringstudentName,intlockoutTime){SqlConnectionconnObj=newSqlConnection();connObj.ConnectionString=Util.StudentDataInsert();connObj.Open();SqlCommandcomm=newSqlCommand("uspCheckLockout",connObj);comm.CommandType=CommandType.Stored程序;comm.Parameters.Add(newSqlParameter("@Studentname",studentName));comm.Parameters.Add(newSqlParameter("@LockoutTime",lockoutTime));varreturnParam=newSqlParameter{ParameterName="@return",Direction=ParameterDirection.ReturnValue};comm.Parameters.Add(返回参数);comm.ExecuteNonQuery();varisLocked=(int)returnParam.Value;connObj.Close();返回被锁定;但是,这有点令人困惑(IMO)通常我在这种情况下所做的是选择我想要的值作为存储过程中的最后一条语句。然后我在命令对象上使用ExecuteScalar来检索值而不是ExecuteNonQuery。PROC:...SQL...SELECT@isLocked方法:publicintIsStudentLocked(stringstudentName,intlockoutTime){using(SqlConnectionconnObj=newSqlConnection()){connObj.ConnectionString=Util.StudentDataInsert();connObj.Open();SqlCommandcomm=newSqlCommand("uspCheckLockout",connObj);comm.CommandType=CommandType.StoredProcedure;comm.Parameters.Add(newSqlParameter("@Studentname",studentName));comm.Parameters.Add(newSqlParameter("@LockoutTime",lockoutTime));返回(int)comm.ExecuteScalar();您应该调用ExecuteScalar而不是ExecuteNonQuery,并在存储过程中将RETURN替换为SELECT。顺便说一下,你应该用using块包装你的连接,所以即使在遇到Close()之前发生了一些异常,它也会被优雅地处理。如果上面@IsLocked存储过程中的输出参数都是C#学习教程的内容:从存储过程返回值到方法分享,如果对大家有用还需要详细了解C#学习教程,希望大家多多关注——System.Data.SqlClient.SqlParameterparamterIsLockedOut=command1.Parameters.Add("@MyParameter",SqlDbType.SmallInt);paramterIsLockedOut.Direction=ParameterDirection.Output;command1.ExecuteNonQuery();intnewValue=(int)paramterIsLockedOut.Value;网络收藏不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: