SqlBulkCopy.NotifyAfter 속성

정의

알림 이벤트를 생성하기 전에 처리할 행의 수를 정의합니다.

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

속성 값

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

예제

다음 콘솔 애플리케이션 데이터 대량 로드는 이미 열려 있는 연결을 사용 하는 방법에 설명 합니다. 속성은 NotifyAfter 테이블에 복사된 50개 행마다 이벤트 처리기가 호출되도록 설정됩니다.

이 예제에서 연결은 먼저 SQL Server 테이블에서 instance 데이터를 읽는 SqlDataReader 데 사용됩니다. 그런 다음 데이터를 대량 복사하기 위해 두 번째 연결이 열립니다. 원본 데이터는 SQL Server 배치할 필요가 없습니다. 에 읽 IDataReader 거나 로 로드할 수 있는 모든 데이터 원본을 DataTable사용할 수 있습니다.

중요

이 샘플은 가져올 대량 복사 샘플 설정에 설명된 대로 작업 테이블을 만들지 않은 경우 실행되지 않습니다. 이 코드는 SqlBulkCopy를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 테이블과 대상 테이블이 동일한 SQL Server instance 있는 경우 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("NotifyAfter Sample");
            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 up the event handler to notify after 50 rows.
                bulkCopy.SqlRowsCopied +=
                    new SqlRowsCopiedEventHandler(OnSqlRowsCopied);
                bulkCopy.NotifyAfter = 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 void OnSqlRowsCopied(
        object sender, SqlRowsCopiedEventArgs e)
    {
        Console.WriteLine("Copied {0} so far...", e.RowsCopied);
    }
    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("NotifyAfter Sample")
            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 up the event handler to notify after 50 rows.
                AddHandler bulkCopy.SqlRowsCopied, AddressOf OnSqlRowsCopied
                bulkCopy.DestinationTableName = _
                 "dbo.BulkCopyDemoMatchingColumns"
                bulkCopy.NotifyAfter = 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 Sub OnSqlRowsCopied(ByVal sender As Object, _
        ByVal args As SqlRowsCopiedEventArgs)
        Console.WriteLine("Copied {0} so far...", args.RowsCopied)
    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

설명

이 속성은 대량 복사 작업의 진행률을 보여 주는 사용자 인터페이스 구성 요소를 위해 설계되었습니다. 알림 이벤트를 생성하기 전에 처리할 행 수를 나타냅니다. NotifyAfter 대량 복사 작업이 진행되는 동안에도 언제든지 속성을 설정할 수 있습니다. 대량 복사 작업 중에 수행된 변경 내용은 다음 알림 후에 적용됩니다. 새 설정은 동일한 instance 모든 후속 작업에 적용됩니다.

가 0보다 작은 숫자로 설정되면 NotifyAfterArgumentOutOfRangeException throw됩니다.

적용 대상

추가 정보