ADO.NET में आउटपुट पैरामीटर मान प्राप्त करें


96

मेरी संग्रहीत प्रक्रिया में एक आउटपुट पैरामीटर है:

@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();
}

जवाबों:


119

अन्य प्रतिक्रिया से पता चलता है यह, लेकिन अनिवार्य रूप से आप सिर्फ एक बनाने की जरूरत 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 से प्रश्न में अपडेट कोड को संपादित करने के लिए।


8
आपको conn.Close()एक usingब्लॉक के अंदर इसकी आवश्यकता नहीं है
मार्कस

1
मुझे लगता है कि int.MaxValue का आपका उपयोग आकार की संपत्ति गलत है। int.MaxValue 2,147,483,647 मान के साथ एक स्थिर है। msdn.microsoft.com/en-us/library/… । इस उदाहरण में गलती हानिरहित है क्योंकि डेटाटाइप इंट है और "निश्चित लंबाई डेटा प्रकारों के लिए, आकार का मान अनदेखा किया गया है।", लेकिन एक शून्य पर्याप्त होगा।
वाल्टर स्टबोसज़

.लव्यू टाइप ऑब्जेक्ट का होता है, इसलिए बिना कास्टिंग के इसे इंट को सीधे असाइन करना काम नहीं करता है।
स्टीफन केनेडी

1
उन लोगों के लिए जो एक DataReader का उपयोग कर रहे हैं, आपको आउटपुट मापदंडों को देखने से पहले इसे बंद करना होगा या डेटा के अंत तक पढ़ना होगा।
गैरी इंग्लिश

56

संग्रहीत प्रक्रिया के साथ एक पाठक का उपयोग करके कुछ ऐसा ही करने की तलाश में, ध्यान दें कि आउटपुट मान प्राप्त करने के लिए पाठक को बंद होना चाहिए।

using (SqlConnection conn = new SqlConnection())
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add parameters
    SqlParameter outputParam = cmd.Parameters.Add("@ID", SqlDbType.Int);
    outputParam.Direction = ParameterDirection.Output;

    conn.Open();

    using(IDataReader reader = cmd.ExecuteReader())
    {
        while(reader.Read())
        {
            //read in data
        }
    }
    // reader is closed/disposed after exiting the using statement
    int id = outputParam.Value;
}

4
मैंने इस तथ्य को याद किया कि आउटपुट पैरामीटर पढ़ने से पहले पाठक को बंद होना चाहिए। यह बात बताने के लिए धन्यवाद!
निकलस मोलर जेपसेन

28

मेरा कोड नहीं, लेकिन एक अच्छा उदाहरण मुझे लगता है

स्रोत: http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624

using System; 
using System.Data; 
using System.Data.SqlClient; 


class OutputParams 
{ 
    [STAThread] 
    static void Main(string[] args) 
    { 

    using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;")) 
    { 
        SqlCommand cmd = new SqlCommand("CustOrderOne", cn); 
        cmd.CommandType=CommandType.StoredProcedure ; 

        SqlParameter parm= new SqlParameter("@CustomerID",SqlDbType.NChar) ; 
        parm.Value="ALFKI"; 
        parm.Direction =ParameterDirection.Input ; 
        cmd.Parameters.Add(parm); 

        SqlParameter parm2= new SqlParameter("@ProductName",SqlDbType.VarChar); 
        parm2.Size=50; 
        parm2.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm2); 

        SqlParameter parm3=new SqlParameter("@Quantity",SqlDbType.Int); 
        parm3.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm3);

        cn.Open(); 
        cmd.ExecuteNonQuery(); 
        cn.Close(); 

        Console.WriteLine(cmd.Parameters["@ProductName"].Value); 
        Console.WriteLine(cmd.Parameters["@Quantity"].Value.ToString());
        Console.ReadLine(); 
    } 
} 

2
हां, यह सही है। बस पैरामीटर के पैरामीटर पैरामीटर सेट करें। आपको cn.Close () लाइन - के उपयोग की आवश्यकता नहीं है {} ब्लॉक इसका ध्यान रखता है।
मुशीनेसिस

6
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
//Create the SqlCommand object
SqlCommand cmd = new SqlCommand(“spAddEmployee”, con);

//Specify that the SqlCommand is a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;

//Add the input parameters to the command object
cmd.Parameters.AddWithValue(“@Name”, txtEmployeeName.Text);
cmd.Parameters.AddWithValue(“@Gender”, ddlGender.SelectedValue);
cmd.Parameters.AddWithValue(“@Salary”, txtSalary.Text);

//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = @EmployeeId”;
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);

//Open the connection and execute the query
con.Open();
cmd.ExecuteNonQuery();

//Retrieve the value of the output parameter
string EmployeeId = outPutParameter.Value.ToString();
}

फ़ॉन्ट http://www.codeproject.com/Articles/748619/ADO-NET-How-to-call-a-stored-procedure-with-output


6
public static class SqlParameterExtensions
{
    public static T GetValueOrDefault<T>(this SqlParameter sqlParameter)
    {
        if (sqlParameter.Value == DBNull.Value 
            || sqlParameter.Value == null)
        {
            if (typeof(T).IsValueType)
                return (T)Activator.CreateInstance(typeof(T));

            return (default(T));
        }

        return (T)sqlParameter.Value;
    }
}


// Usage
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("storedProcedure", conn))
{
   SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int)
   { 
      Direction = ParameterDirection.Output 
   };

   cmd.CommandType = CommandType.StoredProcedure;
   cmd.Parameters.Add(outputIdParam);

   conn.Open();
   cmd.ExecuteNonQuery();

   int result = outputIdParam.GetValueOrDefault<int>();
}

3

आप अपना परिणाम नीचे दिए गए कोड से प्राप्त कर सकते हैं ::

using (SqlConnection conn = new SqlConnection(...))
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add other parameters parameters

    //Add the output parameter to the command object
    SqlParameter outPutParameter = new SqlParameter();
    outPutParameter.ParameterName = "@Id";
    outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
    outPutParameter.Direction = System.Data.ParameterDirection.Output;
    cmd.Parameters.Add(outPutParameter);

    conn.Open();
    cmd.ExecuteNonQuery();

    //Retrieve the value of the output parameter
    string Id = outPutParameter.Value.ToString();

    // *** read output parameter here, how?
    conn.Close();
}

2

SqlParamObject बनाएँ जो आपको मापदंडों पर पहुँच विधियों पर नियंत्रण प्रदान करेगा

:

SqlParameter param = नया SqlParameter ();

अपने पैरामेटर के लिए नाम सेट करें (यह उसी तरह होना चाहिए जैसे आपने अपने डेटाबेस में मान रखने के लिए एक चर घोषित किया होगा)

: param.ParameterName = "@yourParamterName";

आपको आउटपुट डेटा रखने के लिए मूल्य धारक को साफ़ करें

: param.Value = 0;

अपनी पसंद की दिशा निर्धारित करें (आपके मामले में यह आउटपुट होना चाहिए)

: param.Direction = System.Data.ParameterDirection.Output;


1

यह मेरे लिए अधिक स्पष्ट दिखता है:

int? id = outputIdParam.Value DbNull है? डिफ़ॉल्ट (int?): outputIdParam.Value;

हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.