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、を作成し、をに設定DirectionOutput、それをSqlCommandParametersコレクションに追加するだけです。次に、ストアドプロシージャを実行し、パラメーターの値を取得します。

コードサンプルの使用:

// 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年以上、約2万回のビューで、元の投稿の「注意」コメントで指定された理由でコンパイルできなかったと誰も言及しませんでした。いいね。@Walter Staboszと@Stephen Kennedyからの良いコメントに基づいて修正し、@ abatishchevからの質問の更新コード編集に一致させました。


8
ブロックのconn.Close()内側には必要ありませんusing
マーカス

1
サイズプロパティとしてのint.MaxValueの使用は正しくないと思います。int.MaxValueは、値が2,147,483,647の定数です。msdn.microsoft.com/en-us/library/…。この例では、データ型がIntであり、「固定長データ型の場合、Sizeの値は無視されます。」という誤りは無害ですが、ゼロで十分です。
Walter Stabosz 2012年

.Valueはオブジェクト型であるため、キャストせずにそれをintに直接割り当てることはできません。
スティーブンケネディ

1
DataReaderを使用している場合は、出力パラメーターを表示する前に、DataReaderを閉じるか、データの最後まで読み取る必要があります。
Garry English

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
出力パラメーターを読み取る前にリーダーを閉じる必要があるという事実を見逃しました。指摘してくれてありがとう!
NicklasMøllerJepsen 2017

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
はい、これは正しいです。パラメータのParameterDirectionプロパティを設定するだけです。cn.Close()行は必要ありません-using {}ブロックがそれを処理します。
MusiGenesis 2008年

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 = new SqlParameter();

パラメータの名前を設定します(データベースに値を保持する変数を宣言した場合と同じです)

param.ParameterName = "@yourParamterName";

バリューホルダーをクリアして出力データを保持します

param.Value = 0;

選択した方向を設定します(あなたの場合は出力になるはずです)

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


1

それは私にとってより明白に見えます:

int?id = outputIdParam.ValueはDbNullですか?default(int?):outputIdParam.Value;

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.