ADO.NET'te çıktı parametresi değerini alın


96

Depolanan yordamımın bir çıktı parametresi var:

@ID INT OUT

Bunu ado.net kullanarak nasıl alabilirim?

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

Yanıtlar:


120

Diğer yanıt bunu gösterir, ancak esasen sadece bir tane oluşturmanız SqlParameter, Directiondeğerini ayarlamanız Outputve SqlCommand's Parameterskoleksiyonuna eklemeniz gerekir . Daha sonra saklı yordamı yürütün ve parametrenin değerini alın.

Kod örneğinizi kullanarak:

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

Türün, ilan ettiğiniz şeye dönüştürülmesi Parameters[].Valuegerektiğinden, alırken dikkatli olun object. Ve veritabanındaki türle eşleşen ihtiyaçları SqlDbTypeoluşturduğunuzda kullanılır SqlParameter. Sadece konsola çıktı olarak verecekseniz, sadece kullanıyor olabilirsiniz Parameters["@Param"].Value.ToString()(açık veya dolaylı olarak bir Console.Write()veya String.Format()çağrı yoluyla ).

DÜZENLEME: 3.5 yıldan fazla ve neredeyse 20.000 görüntülenme ve hiç kimse orijinal gönderideki "dikkatli ol" yorumumda belirtilen nedenle derlemediğinden bahsetmeye zahmet etmemişti. Güzel. @Walter Stabosz ve @Stephen Kennedy'den gelen iyi yorumlara dayanarak ve @abatishchev'den gelen sorudaki güncelleme kodu düzenlemesiyle eşleşecek şekilde düzeltildi.


8
conn.Close()Bir usingbloğun içinde olmasına gerek yok
— Marcus

1
Size özelliği olarak int.MaxValue kullanımınızın yanlış olduğunu düşünüyorum. int.MaxValue, 2.147.483.647 değerine sahip bir sabittir. msdn.microsoft.com/en-us/library/… . Bu örnekte hata zararsızdır çünkü veri türü Int ve "Sabit uzunluklu veri türleri için Boyut değeri göz ardı edilir.", Ancak sıfır yeterli olacaktır.
— Walter Stabosz

.Value nesne türünde olduğundan, onu çevrim yapmadan doğrudan bir int'e atamak işe yaramayacaktır.
— Stephen Kennedy

1
DataReader kullananlar için, çıktı parametrelerini görüntülemeden önce onu kapatmanız veya verilerin sonuna kadar okumalısınız.
— Garry English

56

Saklanan yordamla okuyucu kullanarak benzer bir şey yapmak isteyenler için, çıktı değerini almak için okuyucunun kapatılması gerektiğini unutmayın.

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
Çıkış parametresini okumadan önce okuyucunun kapatılması gerektiği gerçeğini kaçırdım. Bunu belirttiğiniz için teşekkürler!
— Nicklas Møller Jepsen

28

Benim kodum değil ama bence iyi bir örnek

kaynak: 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
Evet, bu doğru. Sadece parametrenin ParameterDirection özelliğini ayarlayın. Cn.Close () satırına ihtiyacınız yok - {} kullanan blok bunu halleder.
— MusiGenesis

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

Yazı tipi 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

Sonucunuzu aşağıdaki koddan alabilirsiniz:

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

Parametrelerdeki yöntemlere erişim için denetim sağlayacak SqlParamObject'i oluşturun

:

SqlParameter parametresi = new SqlParameter ();

Parametrenizin adını ayarlayın (DataBase'inizdeki değeri tutmak için bir değişken bildirdiğinizle aynı olmalıdır)

: param.ParameterName = "@yourParamterName";

Çıktı verilerini tutması için değer sahibini temizleyin

: param.Value = 0;

Seçiminizin Yönünü Ayarlayın (Sizin durumunuzda, Çıktı olmalıdır)

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


1

Bu benim için daha açık görünüyor:

int? id = outputIdParam.Value DbNull mu? varsayılan (int?): outputIdParam.Value;

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.