次の方法で共有


コマンドの実行

適用対象: .NET Framework .NET .NET Standard

ADO.NET のダウンロード

Microsoft SqlClient Data Provider for SQL Server には、DbCommand から継承される SqlCommand オブジェクトがあります。 このオブジェクトでは、次の表に示すように、コマンドの種類と必要な戻り値に基づいて各コマンドを実行するためのメソッドが公開されています。

コマンド 戻り値
ExecuteReader DataReader オブジェクトを返します。
ExecuteScalar 単一のスカラー値を返します。
ExecuteNonQuery 行を一切返さないコマンドを実行します。
ExecuteXMLReader XmlReader を返します。 SqlCommand オブジェクトでのみ使用できます。

厳密に型指定された各コマンド オブジェクトは、次の表に示す CommandType 列挙値をサポートしています。これらの列挙値を使用してコマンド文字列の解釈方法を指定できます。

CommandType 説明
Text データ ソース側で実行されるステートメントを定義する SQL コマンド。
StoredProcedure ストアド プロシージャの名前。 呼び出す Parameters メソッドに関係なく、コマンドの Execute プロパティを使用して入力パラメーターと出力パラメーターにアクセスし、戻り値を取得できます。
TableDirect テーブルの名前。

重要

ExecuteReader を使用した場合は、DataReader を閉じるまで戻り値および出力パラメーターにアクセスすることはできません。

SqlCommand オブジェクトを作成し、そのプロパティを設定することによってストアド プロシージャを実行するコード サンプルを次に示します。 ストアド プロシージャへの入力パラメーターは、SqlParameter オブジェクトを使って指定します。 このコマンドを ExecuteReader メソッドで実行し、SqlDataReader からの出力をコンソール ウィンドウに表示します。

static void GetSalesByCategory(string connectionString,
    string categoryName)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        // Create the command and set its properties.
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandText = "SalesByCategory";
        command.CommandType = CommandType.StoredProcedure;

        // Add the input parameter and set its properties.
        SqlParameter parameter = new SqlParameter();
        parameter.ParameterName = "@CategoryName";
        parameter.SqlDbType = SqlDbType.NVarChar;
        parameter.Direction = ParameterDirection.Input;
        parameter.Value = categoryName;

        // Add the parameter to the Parameters collection.
        command.Parameters.Add(parameter);

        // Open the connection and execute the reader.
        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader())
        {
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
                }
            }
            else
            {
                Console.WriteLine("No rows found.");
            }
            reader.Close();
        }
    }
}

コマンドのトラブルシューティング

Microsoft SqlClient Data Provider for SQL Server では、失敗したコマンド実行に関連する断続的な問題を検出できるようにするための診断カウンターが追加されています。 詳細については、「SqlClient の診断カウンター」を参照してください。

関連項目