其他反應(yīng)表明這一點(diǎn),但實(shí)際上你只需要?jiǎng)?chuàng)建一個(gè)SqlParameter
,設(shè)置Direction
來(lái)Output
,并把它添加到SqlCommand
的Parameters
集合。然后執(zhí)行存儲(chǔ)過(guò)程并獲取參數(shù)的值。
使用您的代碼示例:
// 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();}
在獲取時(shí)要小心Parameters[].Value
,因?yàn)樾枰獙㈩愋娃D(zhuǎn)換為object
您聲明的類型。而SqlDbType
當(dāng)您創(chuàng)建使用SqlParameter
需求來(lái)匹配數(shù)據(jù)庫(kù)類型。如果您只是將其輸出到控制臺(tái),您可能只是在使用Parameters["@Param"].Value.ToString()
(通過(guò)Console.Write()
或String.Format()
調(diào)用顯式或隱式)。