另一个响应显示了这一点,但实际上您只需要创建一个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
为您声明的类型。和SqlDbType
在您创建SqlParameter
需要匹配数据库中的类型时使用。如果要仅将其输出到控制台,则可能只是在使用Parameters["@Param"].Value.ToString()
(通过Console.Write()
or String.Format()
调用显式或隐式)。
编辑:超过3.5年的时间和近2万的视图,没有人不愿意提及它甚至由于原始帖子中“小心”注释中指定的原因而没有编译。真好 根据@Walter Stabosz和@Stephen Kennedy的好评,并与@abatishchev中问题中的更新代码进行匹配,对它进行了修复。
conn.Close()
它作为一个using
块