다른 응답 프로그램이 있지만, 본질적으로 단지를 만들 필요가 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 년이 넘고 거의 20k의 조회수를 기록했으며 아무도 원래 게시물의 "주의"댓글에 지정된 이유로 컴파일하지 않았다고 언급하지 않았습니다. 좋은. @Walter Stabosz 및 @Stephen Kennedy의 좋은 의견을 기반으로 수정하고 @abatishchev의 질문에있는 업데이트 코드 편집과 일치하도록 수정했습니다.
conn.Close()내부로 필요하지 않습니다using