在ADO.NET中獲取輸出參數值我的存儲過程有一個輸出參數:@ID INT OUT如何使用ado.net檢索此內容?using (SqlConnection conn = new SqlConnection(...)){
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add parameters
conn.Open();
// *** read output parameter here, how?
conn.Close();}
3 回答
飲歌長嘯
TA貢獻1951條經驗 獲得超3個贊
其他反應表明這一點,但實際上你只需要創建一個SqlParameter,設置Direction來Output,并把它添加到SqlCommand的Parameters集合。然后執行存儲過程并獲取參數的值。
使用您的代碼示例:
// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'susing (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 回答
- 0 關注
- 739 瀏覽
添加回答
舉報
0/150
提交
取消
