他の応答はこれを示していますが、基本的には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()
またはString.Format()
呼び出しを介して)を使用している可能性があります。
編集:3.5年以上、約2万回のビューで、元の投稿の「注意」コメントで指定された理由でコンパイルできなかったと誰も言及しませんでした。いいね。@Walter Staboszと@Stephen Kennedyからの良いコメントに基づいて修正し、@ abatishchevからの質問の更新コード編集に一致させました。
conn.Close()
内側には必要ありませんusing