SqlBatch.BatchCommands 属性

定义

批处理中包含的 SqlBatchCommandCollection命令列表。

public:
 property Microsoft::Data::SqlClient::SqlBatchCommandCollection ^ BatchCommands { Microsoft::Data::SqlClient::SqlBatchCommandCollection ^ get(); };
public Microsoft.Data.SqlClient.SqlBatchCommandCollection BatchCommands { get; }
member this.BatchCommands : Microsoft.Data.SqlClient.SqlBatchCommandCollection
Public ReadOnly Property BatchCommands As SqlBatchCommandCollection

属性值

示例

以下示例创建 SqlConnectionSqlBatch,然后将多个 SqlBatchCommand 对象添加到批处理。 然后,它执行批处理,创建 SqlDataReader。 该示例通读批处理命令的结果,并将其写入控制台。 最后,该示例关闭 , SqlDataReader 然后在 SqlConnection 块退出范围时 using 关闭 。

using Microsoft.Data.SqlClient;

class Program
{
    static void Main()
    {
        string str = "Data Source=(local);Initial Catalog=Northwind;"
        + "Integrated Security=SSPI;Encrypt=False";
        RunBatch(str);
    }

    static void RunBatch(string connString)
    {
        using var connection = new SqlConnection(connString);
        connection.Open();

        var batch = new SqlBatch(connection);

        const int count = 10;
        const string parameterName = "parameter";
        for (int i = 0; i < count; i++)
        {
            var batchCommand = new SqlBatchCommand($"SELECT @{parameterName} as value");
            batchCommand.Parameters.Add(new SqlParameter(parameterName, i));
            batch.BatchCommands.Add(batchCommand);
        }

        // Optionally Prepare
        batch.Prepare();

        var results = new List<int>(count);
        using (SqlDataReader reader = batch.ExecuteReader())
        {
            do
            {
                while (reader.Read())
                {
                    results.Add(reader.GetFieldValue<int>(0));
                }
            } while (reader.NextResult());
        }
        Console.WriteLine(string.Join(", ", results));
    }
}

适用于