我的存储过程有一个输出参数:
@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
,并将其添加到SqlCommand
的Parameters
集合。然后执行存储过程,得到参数的值。
使用您的代码示例:
// 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/