Kobarin's Development Blog

C#やASP.NETなどについての記録です。

C#から、ストアドプロシージャの戻り値を取得する最短(?)コード

2行でいけます。

using (SqlConnection cn = new SqlConnection(strConnectionString))
{
  using (SqlCommand cmd = cn.CreateCommand())
  {
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@name", SqlDbType.NVarChar, 200).Value = txtName.Text;
    cmd.Parameters.Add("@RetValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
    cn.Open();
    cmd.ExecuteNonQuery();
    strResult = cmd.Parameters["@RetValue"].Value.ToString();
    cn.Close();
  }
}