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

标签 c# .net 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();
}

最佳答案

另一个响应显示了这一点,但本质上您只需要创建一个 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 时要小心,因为类型需要从 object 转换为您声明的类型。创建 SqlParameter 时使用的 SqlDbType 需要与数据库中的类型相匹配。如果您只想将它​​输出到控制台,您可能只是使用 Parameters["@Param"].Value.ToString()(通过 Console 显式或隐式地使用。 Write()String.Format() 调用)。

编辑:超过 3.5 年和将近 20k 的浏览量,没有人提到它甚至没有编译,原因是我在原始帖子中的“小心”评论中指定的原因。好的。根据@Walter Stabosz 和@Stephen Kennedy 的好评修复了它,并匹配来自@abatishchev 的问题中的更新代码编辑。

关于c# - 在 ADO.NET 中获取输出参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/290652/

相关文章:

azure - ado.net 和 SQL Azure 目前接受的策略是什么?

c# - 检测到 Entity Framework 自引用循环

c# - Windows Azure 服务总线队列 - MessageSender 还是 QueueClient?

.net - Resharper:代码风格共享 - 强制执行

c# - 使用 .net 学习多线程的好资源?

c# - 删除和更新查询在 ADO.NET 中不起作用

c# - 在服务器套接字 C# 中获取有关客户端的数据

c# - Azure Function Apps - 使用登录用户的凭据来读取/更新 Azure 资源

c# - System.Serializable 在 Unity 中的 List<MyClass> 上不起作用?

entity-framework - EF4 创建自定义 DbFactoryProvider 和其他 Db* 类