अन्य प्रतिक्रिया से पता चलता है यह, लेकिन अनिवार्य रूप से आप सिर्फ एक बनाने की जरूरत 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 कैनेडी की अच्छी टिप्पणियों के आधार पर तय किया और @abatishchev से प्रश्न में अपडेट कोड को संपादित करने के लिए।
conn.Close()एकusingब्लॉक के अंदर इसकी आवश्यकता नहीं है