Các chương trình phản ứng khác này, nhưng về cơ bản bạn chỉ cần tạo ra một SqlParameter
, thiết lập Direction
để Output
, và thêm nó vào SqlCommand
's Parameters
sưu tập. Sau đó thực hiện thủ tục đã lưu trữ và nhận giá trị của tham số.
Sử dụng mẫu mã của bạn:
// 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();
}
Hãy cẩn thận khi lấy Parameters[].Value
, vì kiểu cần được chuyển từ kiểu object
mà bạn đang khai báo. Và SqlDbType
được sử dụng khi bạn tạo SqlParameter
nhu cầu để phù hợp với loại trong cơ sở dữ liệu. Nếu bạn chỉ xuất nó ra bảng điều khiển, bạn có thể đang sử dụng Parameters["@Param"].Value.ToString()
(rõ ràng hoặc ẩn ý thông qua một Console.Write()
hoặc một String.Format()
cuộc gọi).
CHỈNH SỬA: Hơn 3,5 năm và gần 20 nghìn lượt xem và không ai bận tâm đến việc nó thậm chí không được biên dịch vì lý do được chỉ định trong nhận xét "hãy cẩn thận" của tôi trong bài đăng gốc. Đẹp. Đã sửa lỗi dựa trên nhận xét tốt từ @Walter Stabosz và @Stephen Kennedy và để khớp với chỉnh sửa mã cập nhật trong câu hỏi từ @abatishchev.
conn.Close()
nó bên trong mộtusing
khối