在ADO.NET中获取输出参数值

我的存储过程有一个输出参数:

@ID INT OUT 

我怎样才能使用ado.net检索这个?

 using (SqlConnection conn = new SqlConnection(...)) { SqlCommand cmd = new SqlCommand("sproc", conn); cmd.CommandType = CommandType.StoredProcedure; // add parameters conn.Open(); // *** read output parameter here, how? conn.Close(); } 

另一个响应显示了这一点,但基本上只需要创build一个SqlParameter ,将Direction设置为Output ,并将其添加到SqlCommandParameters集合中。 然后执行存储过程并获取参数的值。

使用你的代码示例:

 // SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s using (SqlConnection conn = new SqlConnection(connectionString)) using (SqlCommand cmd = new SqlCommand("sproc", conn)) { // Create parameter with Direction as Output (and correct name and type) SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int) { Direction = ParameterDirection.Output }; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(outputIdParam); conn.Open(); cmd.ExecuteNonQuery(); // Some various ways to grab the output depending on how you would like to // handle a null value returned from the query (shown in comment for each). // Note: You can use either the SqlParameter variable declared // above or access it through the Parameters collection by name: // outputIdParam.Value == cmd.Parameters["@ID"].Value // Throws FormatException int idFromString = int.Parse(outputIdParam.Value.ToString()); // Throws InvalidCastException int idFromCast = (int)outputIdParam.Value; // idAsNullableInt remains null int? idAsNullableInt = outputIdParam.Value as int?; // idOrDefaultValue is 0 (or any other value specified to the ?? operator) int idOrDefaultValue = outputIdParam.Value as int? ?? default(int); conn.Close(); } 

获取Parameters[].Value时要小心,因为types需要从object为您声明的types。 而创buildSqlParameter时使用的SqlDbType需要匹配数据库中的types。 如果你打算只输出它到控制台,你可能只是使用Parameters["@Param"].Value.ToString() (通过Console.Write()String.Format()调用显式或隐式地)。

编辑:超过3.5年,近20K的意见,没有人曾经提到,它甚至没有编译原因在我的“小心”评论中指定的原因原来的职位。 尼斯。 修正了它基于@Walter Stabosz和@Stephen Kennedy的好评,并匹配来自@abatishchev的问题中的更新代码编辑。

对于任何想用存储过程使用读取器来做类似的事情,请注意阅读器必须closures以检索输出值。

 using (SqlConnection conn = new SqlConnection()) { SqlCommand cmd = new SqlCommand("sproc", conn); cmd.CommandType = CommandType.StoredProcedure; // add parameters SqlParameter outputParam = cmd.Parameters.Add("@ID", SqlDbType.Int); outputParam.Direction = ParameterDirection.Output; conn.Open(); using(IDataReader reader = cmd.ExecuteReader()) { while(reader.Read()) { //read in data } } // reader is closed/disposed after exiting the using statement int id = outputParam.Value; } 

不是我的代码,而是我想的一个很好的例子

来源: http : //www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624

 using System; using System.Data; using System.Data.SqlClient; class OutputParams { [STAThread] static void Main(string[] args) { using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;")) { SqlCommand cmd = new SqlCommand("CustOrderOne", cn); cmd.CommandType=CommandType.StoredProcedure ; SqlParameter parm= new SqlParameter("@CustomerID",SqlDbType.NChar) ; parm.Value="ALFKI"; parm.Direction =ParameterDirection.Input ; cmd.Parameters.Add(parm); SqlParameter parm2= new SqlParameter("@ProductName",SqlDbType.VarChar); parm2.Size=50; parm2.Direction=ParameterDirection.Output; cmd.Parameters.Add(parm2); SqlParameter parm3=new SqlParameter("@Quantity",SqlDbType.Int); parm3.Direction=ParameterDirection.Output; cmd.Parameters.Add(parm3); cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); Console.WriteLine(cmd.Parameters["@ProductName"].Value); Console.WriteLine(cmd.Parameters["@Quantity"].Value.ToString()); Console.ReadLine(); } } 
 string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; using (SqlConnection con = new SqlConnection(ConnectionString)) { //Create the SqlCommand object SqlCommand cmd = new SqlCommand(“spAddEmployee”, con); //Specify that the SqlCommand is a stored procedure cmd.CommandType = System.Data.CommandType.StoredProcedure; //Add the input parameters to the command object cmd.Parameters.AddWithValue(“@Name”, txtEmployeeName.Text); cmd.Parameters.AddWithValue(“@Gender”, ddlGender.SelectedValue); cmd.Parameters.AddWithValue(“@Salary”, txtSalary.Text); //Add the output parameter to the command object SqlParameter outPutParameter = new SqlParameter(); outPutParameter.ParameterName = “@EmployeeId”; outPutParameter.SqlDbType = System.Data.SqlDbType.Int; outPutParameter.Direction = System.Data.ParameterDirection.Output; cmd.Parameters.Add(outPutParameter); //Open the connection and execute the query con.Open(); cmd.ExecuteNonQuery(); //Retrieve the value of the output parameter string EmployeeId = outPutParameter.Value.ToString(); } 

字体http://www.codeproject.com/Articles/748619/ADO-NET-How-to-call-a-stored-procedure-with-output

 public static class SqlParameterExtensions { public static T GetValueOrDefault<T>(this SqlParameter sqlParameter) { if (sqlParameter.Value == DBNull.Value || sqlParameter.Value == null) { if (typeof(T).IsValueType) return (T)Activator.CreateInstance(typeof(T)); return (default(T)); } return (T)sqlParameter.Value; } } // Usage using (SqlConnection conn = new SqlConnection(connectionString)) using (SqlCommand cmd = new SqlCommand("storedProcedure", conn)) { SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int) { Direction = ParameterDirection.Output }; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(outputIdParam); conn.Open(); cmd.ExecuteNonQuery(); int result = outputIdParam.GetValueOrDefault<int>(); } 

你可以通过下面的代码得到你的结果::

 using (SqlConnection conn = new SqlConnection(...)) { SqlCommand cmd = new SqlCommand("sproc", conn); cmd.CommandType = CommandType.StoredProcedure; // add other parameters parameters //Add the output parameter to the command object SqlParameter outPutParameter = new SqlParameter(); outPutParameter.ParameterName = "@Id"; outPutParameter.SqlDbType = System.Data.SqlDbType.Int; outPutParameter.Direction = System.Data.ParameterDirection.Output; cmd.Parameters.Add(outPutParameter); conn.Open(); cmd.ExecuteNonQuery(); //Retrieve the value of the output parameter string Id = outPutParameter.Value.ToString(); // *** read output parameter here, how? conn.Close(); } 

这对我来说更加明确:

诠释? id = outputIdParam.Value是DbNull? default(int?):outputIdParam.Value;