다음을 통해 공유


SqlBulkCopy.BatchSize 속성

정의

각 일괄 처리의 행 수입니다. 각 일괄 처리가 끝나면 일괄 처리의 행이 서버로 보내집니다.

public:
 property int BatchSize { int get(); void set(int value); };
public int BatchSize { get; set; }
member this.BatchSize : int with get, set
Public Property BatchSize As Integer

속성 값

속성의 BatchSize 정수 값이거나, 값이 설정되지 않은 경우 0입니다.

예제

다음 콘솔 애플리케이션은 50개 행의 일괄 처리로 데이터를 대량 로드하는 방법을 보여 줍니다. 트랜잭션의 작동 방식을 BatchSize 보여 주는 예제는 트랜잭션 및 대량 복사 작업을 참조하세요.

이 예제에서 원본 데이터는 먼저 SQL Server 테이블에서 인스턴스로 SqlDataReader 읽습니다. 원본 데이터는 SQL Server에 있을 필요가 없습니다. 에 읽거나 로드DataTable할 수 있는 모든 데이터 원본을 IDataReader 사용할 수 있습니다.

중요합니다

작업 테이블을 대량 복사 예제 설정에 설명된 대로 생성하지 않으면 이 샘플은 실행되지 않습니다. 이 코드는 SqlBulkCopy를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 및 대상 테이블이 동일한 SQL Server 인스턴스에 있는 경우 Transact-SQL INSERT ... SELECT 문을 사용하여 데이터를 복사하는 것이 더 쉽고 빠릅니다.

using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = GetConnectionString();
        // Open a sourceConnection to the AdventureWorks database.
        using (SqlConnection sourceConnection =
                   new SqlConnection(connectionString))
        {
            sourceConnection.Open();

            // Perform an initial count on the destination table.
            SqlCommand commandRowCount = new SqlCommand(
                "SELECT COUNT(*) FROM " +
                "dbo.BulkCopyDemoMatchingColumns;",
                sourceConnection);
            long countStart = System.Convert.ToInt32(
                commandRowCount.ExecuteScalar());
            Console.WriteLine("Starting row count = {0}", countStart);

            // Get data from the source table as a SqlDataReader.
            SqlCommand commandSourceData = new SqlCommand(
                "SELECT ProductID, Name, " +
                "ProductNumber " +
                "FROM Production.Product;", sourceConnection);
            SqlDataReader reader =
                commandSourceData.ExecuteReader();

            // Create the SqlBulkCopy object using a connection string.
            // In the real world you would not use SqlBulkCopy to move
            // data from one table to the other in the same database.
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoMatchingColumns";

                // Set the BatchSize.
                bulkCopy.BatchSize = 50;

                try
                {
                    // Write from the source to the destination.
                    bulkCopy.WriteToServer(reader);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    // Close the SqlDataReader. The SqlBulkCopy
                    // object is automatically closed at the end
                    // of the using block.
                    reader.Close();
                }

                // Perform a final count on the destination
                // table to see how many rows were added.
                long countEnd = System.Convert.ToInt32(
                    commandRowCount.ExecuteScalar());
                Console.WriteLine("Ending row count = {0}", countEnd);
                Console.WriteLine("{0} rows were added.", countEnd - countStart);
                Console.WriteLine("Press Enter to finish.");
                Console.ReadLine();
            }
        }
    }

    private static string GetConnectionString()
        // To avoid storing the sourceConnection string in your code,
        // you can retrieve it from a configuration file.
    {
        return "Data Source=(local); " +
            " Integrated Security=true;" +
            "Initial Catalog=AdventureWorks;";
    }
}
Imports System.Data.SqlClient

Module Module1
    Sub Main()
        Dim connectionString As String = GetConnectionString()

        ' Open a connection to the AdventureWorks database.
        Using sourceConnection As SqlConnection = _
           New SqlConnection(connectionString)
            sourceConnection.Open()

            ' Perform an initial count on the destination table.
            Dim commandRowCount As New SqlCommand( _
            "SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", _
                sourceConnection)
            Dim countStart As Long = _
               System.Convert.ToInt32(commandRowCount.ExecuteScalar())
            Console.WriteLine("Starting row count = {0}", countStart)

            ' Get data from the source table as a SqlDataReader.
            Dim commandSourceData As SqlCommand = New SqlCommand( _
               "SELECT ProductID, Name, ProductNumber " & _
               "FROM Production.Product;", sourceConnection)
            Dim reader As SqlDataReader = commandSourceData.ExecuteReader

            ' Create the SqlBulkCopy object using a connection string. 
            ' In the real world you would not use SqlBulkCopy to move
            ' data from one table to the other in the same database.
            Using bulkCopy As SqlBulkCopy = _
              New SqlBulkCopy(connectionString)
                bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"

                ' Set the BatchSize.
                bulkCopy.BatchSize = 50

                Try
                    ' Write from the source to the destination.
                    bulkCopy.WriteToServer(reader)

                Catch ex As Exception
                    Console.WriteLine(ex.Message)

                Finally
                    ' Close the SqlDataReader. The SqlBulkCopy
                    ' object is automatically closed at the end
                    ' of the Using block.
                    reader.Close()
                End Try
            End Using

            ' Perform a final count on the destination table
            ' to see how many rows were added.
            Dim countEnd As Long = _
                System.Convert.ToInt32(commandRowCount.ExecuteScalar())
            Console.WriteLine("Ending row count = {0}", countEnd)
            Console.WriteLine("{0} rows were added.", countEnd - countStart)

            Console.WriteLine("Press Enter to finish.")
            Console.ReadLine()
        End Using
    End Sub

    Private Function GetConnectionString() As String
        ' To avoid storing the sourceConnection string in your code, 
        ' you can retrieve it from a configuration file. 
        Return "Data Source=(local);" & _
            "Integrated Security=true;" & _
            "Initial Catalog=AdventureWorks;"
    End Function
End Module

설명

BatchSize 행을 처리했거나 대상 데이터 원본으로 보낼 행이 더 이상 없는 경우, 일괄 처리가 완료됩니다.

0(기본값)은 각 WriteToServer 작업이 단일 일괄 처리임을 나타냅니다.

인스턴스가 SqlBulkCopy 옵션 없이 UseInternalTransaction 선언된 경우 행은 한 번에 서버 BatchSize 행으로 전송되지만 트랜잭션 관련 작업은 수행되지 않습니다. 적용되는 경우 UseInternalTransaction 행의 각 일괄 처리는 별도의 트랜잭션으로 삽입됩니다.

속성은 BatchSize 언제든지 설정할 수 있습니다. 대량 복사가 이미 진행 중인 경우 현재 일괄 처리의 크기는 이전 일괄 처리 크기에 따라 조정됩니다. 후속 일괄 처리는 새 크기를 사용합니다. BatchSize 작업이 이미 진행 중인 동안 WriteToServer 처음에 0이고 변경된 경우 해당 작업은 데이터를 단일 일괄 처리로 로드합니다. 동일한 SqlBulkCopy 인스턴스에 대한 모든 후속 WriteToServer 작업은 새 BatchSize작업을 사용합니다.

적용 대상

추가 정보