Dil

Tek bir toplu kopyalama işlemi

SQL Server toplu kopyalama işlemi gerçekleştirmenin en basit yaklaşımı, veritabanında tek bir işlem gerçekleştirmektir. Varsayılan olarak, toplu kopyalama işlemi yalıtılmış bir işlem olarak gerçekleştirilir: Kopyalama işlemi işlem yapılmamış bir şekilde gerçekleşir ve geri döndürme fırsatı yoktur.

Not

Bir hatadan sonra toplu kopyalamanın tamamını veya bir kısmını geri almak için, parti başına işlemler için SqlBulkCopyOptions.UseInternalTransaction belirtin veya kopyalamayı mevcut bir işlem içinde gerçekleştirin. SqlBulkCopy ayrıca, bağlantı örtük veya açıkça katılmışsa System.Transactions ile de çalışır.

Daha fazla bilgi için İşlem ve Toplu Kopyalama İşlemleri bölümüne bakın.

Toplu kopyalama işlemi gerçekleştirmeye yönelik genel adımlar şunlardır:

  1. Kaynak sunucuya bağlanın ve kopyalanacak verileri alın. Veri, bir IDataReader veya DataTable nesnesinden alınabiliyorsa, başka kaynaklardan da gelebilir.

  2. Hedef sunucuya bağlanın (sizin için bir bağlantı kurmak istemiyorsanız SqlBulkCopy ).

  3. SqlBulkCopy nesnesini oluşturun ve gerekli özellikleri ayarlayın.

  4. DestinationTableName özelliğini, toplu ekleme işlemi için hedef tabloyu gösterecek şekilde ayarlayın.

  5. Yöntemlerden birini WriteToServer çağırın.

  6. İsteğe bağlı olarak, özellikleri güncelleştirin ve gerektiğinde yeniden çağırin WriteToServer .

  7. çağrısı gerçekleştirin Closeveya toplu kopyalama işlemlerini bir Using deyim içinde sarmalayın.

Dikkat

Eşleşen kaynak ve hedef sütun veri türlerini kullanın. Türler eşleşmiyorsa, SqlBulkCopy her bir kaynak değeri Value için geçerli kurallarla hedef veri türüne dönüştürmeye çalışır. Dönüştürmeler performansı etkileyebilir ve beklenmeyen hatalara neden olabilir. Örneğin, Double öğesinden Decimal öğesine dönüştürme bazı değerler için başarısız olabilir.

Örnek

Aşağıdaki konsol uygulaması, verilerin SqlBulkCopy sınıfıyla nasıl yükleneceğini gösterir. Örnek, SQL Server SqlDataReader veritabanındaki Production.Product verilerini aynı veritabanındaki benzer bir tabloya kopyalamak için AdventureWorks öğesini kullanır.

Önemli

Bu örneği çalıştırmadan önce , Toplu Kopyalama Örneği Kurulumu bölümünde açıklanan iş tablolarını oluşturun. Örnek, SqlBulkCopy söz dizimini göstermektedir. Kaynak ve hedef tablolar aynı SQL Server örneğindeyse, daha hızlı bir kopya için bir Transact-SQL (T-SQL) INSERT ... SELECT deyimi kullanın.

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

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

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

        // Open the destination connection. In the real world you would
        // not use SqlBulkCopy to move data from one table to the other
        // in the same database. This is for demonstration purposes only.
        using (SqlConnection destinationConnection =
                   new(connectionString))
        {
            destinationConnection.Open();

            // Set up the bulk copy object.
            // Note that the column positions in the source
            // data reader match the column positions in
            // the destination table so there is no need to
            // map columns.
            using (SqlBulkCopy bulkCopy =
                       new(destinationConnection))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoMatchingColumns";

                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 = Convert.ToInt32(
                commandRowCount.ExecuteScalar());
            Console.WriteLine($"Ending row count = {countEnd}");
            Console.WriteLine($"{countEnd - countStart} rows were added.");
            Console.WriteLine("Press Enter to finish.");
            Console.ReadLine();
        }
    }
}
Imports Microsoft.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 New SqlCommand( _
               "SELECT ProductID, Name, ProductNumber " & _
               "FROM Production.Product;", sourceConnection)
            Dim reader As SqlDataReader = commandSourceData.ExecuteReader

            ' Open the destination connection. In the real world you would
            ' not use SqlBulkCopy to move data from one table to the other
            ' in the same database. This is for demonstration purposes only.
            Using destinationConnection As SqlConnection = _
                New SqlConnection(connectionString)
                destinationConnection.Open()

                ' Set up the bulk copy object.
                ' The column positions in the source data reader
                ' match the column positions in the destination table,
                ' so there is no need to map columns.
                Using bulkCopy As SqlBulkCopy = _
                  New SqlBulkCopy(destinationConnection)
                    bulkCopy.DestinationTableName = _
                    "dbo.BulkCopyDemoMatchingColumns"

                    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 Using
    End Sub

    Private Function GetConnectionString() As String
        Throw New NotImplementedException()
    End Function
End Module

Transact-SQL ve Komut Sınıfı Kullanarak Toplu Kopyalama İşlemi Gerçekleştirme

Aşağıdaki örnek, ExecuteNonQuery deyimini yürütmek için BULK INSERT yönteminin nasıl kullanılacağını göstermektedir.

Not

Veri kaynağının dosya yolu sunucuya göredir. Toplu kopyalama işleminin başarılı olması için sunucu işleminin bu yola erişimi olmalıdır.

Using connection As SqlConnection = New SqlConnection(connectionString)
Dim queryString As String = _
    "BULK INSERT Northwind.dbo.[Order Details] FROM " & _
    "'f:\mydata\data.tbl' WITH (FORMATFILE='f:\mydata\data.fmt' )"
connection.Open()
Dim command As New SqlCommand(queryString, connection)

command.ExecuteNonQuery()
End Using
using (SqlConnection connection = new SqlConnection(connectionString))
{
string queryString =  "BULK INSERT Northwind.dbo.[Order Details] " +
    @"FROM 'f:\mydata\data.tbl' " +
    @"WITH ( FORMATFILE='f:\mydata\data.fmt' )";
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);

command.ExecuteNonQuery();
}

Ayrıca bkz.