输入 - 输出参数同一次调用存储过程 - C#

时间:2013-04-18 15:10:08

标签: sql-server-2008 c#-3.0

using (var con = connection)
            {
                con.Open();
                using (var cmd = new SqlCommand("usp_Students", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlParameter sp = cmd.Parameters.AddWithValue("@StudentIDs", studentId);
                    sp.SqlDbType = SqlDbType.Structured;
                    cmd.ExecuteNonQuery();
                }
            }

我正在为存储过程输入一个值,但在这种情况下我想要获取一个值。如何在上面的代码中加入输出?

CREATE PROCEDURE usp_Students
      @StudentId Students READONLY,
      @NumberOfStudents INT OUTPUT,

1 个答案:

答案 0 :(得分:0)

试试这种方式

using (var con = connection)
{
    con.Open();
    using (var cmd = new SqlCommand("usp_Students", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter sp = cmd.Parameters.AddWithValue("@StudentIDs", studentId);
        sp.SqlDbType = SqlDbType.Structured;

        SqlParameter code = new SqlParameter("@NumberOfStudents", SqlDbType.Int);
        code.Direction = ParameterDirection.Output;
        cmd.Parameters.Add(code);

        cmd.ExecuteNonQuery();

        // Getting output value
        int NumberOfStudent = Convert.ToInt32(cmd.Parameters["@NumberOfStudents"].Value);

    }
}

谢谢

的Manoj