将值从存储过程返回到方法

时间:2012-07-06 21:50:10

标签: c# stored-procedures

我有一个存储过程,它返回学生是否被锁定:

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));

    }

3 个答案:

答案 0 :(得分:18)

要在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();
    }
}

答案 1 :(得分:3)

你应该调用ExecuteScalar而不是ExecuteNonQuery,并在你的存储过程中用RET替换RETURN。

顺便说一下,你应该用using块包裹你的连接,所以即使遇到Close()之前发生了一些异常,它也会被妥善处理。

答案 2 :(得分:0)

如果@IsLocked存储过程中的输出参数

System.Data.SqlClient.SqlParameter paramterIsLockedOut = command1.Parameters.Add("@MyParameter", SqlDbType.SmallInt);
paramterIsLockedOut.Direction = ParameterDirection.Output;
command1.ExecuteNonQuery();

int newValue = (int)paramterIsLockedOut.Value;
相关问题