Lingua

Operazioni di copia in massa singole

L'approccio più semplice per eseguire un'operazione di copia bulk di SQL Server consiste nell'eseguire una singola operazione su un database. Per impostazione predefinita, una copia bulk viene eseguita come un'operazione isolata: l'operazione di copia avviene in modalità non transazionale, senza la possibilità di eseguirne il rollback.

Nota

Per eseguire il rollback di una copia bulk o parte di una copia bulk dopo un errore, specificare SqlBulkCopyOptions.UseInternalTransaction per le transazioni per batch o eseguire la copia all'interno di una transazione esistente. SqlBulkCopy funziona anche con System.Transactions se la connessione viene arruolata in modo implicito o esplicito.

Per altre informazioni, vedere Transazioni e operazioni di copia di massa.

I passaggi generali per l'esecuzione di un'operazione di copia bulk sono i seguenti:

  1. Connettersi al server di origine e ottenere i dati da copiare. I dati possono provenire anche da altre origini, se possono essere recuperati da un oggetto IDataReader o DataTable.

  2. Connettersi al server di destinazione, a meno che non vogliate che SqlBulkCopy stabilisca una connessione per voi.

  3. Creare l'oggetto SqlBulkCopy e impostare le proprietà necessarie.

  4. Impostare la proprietà DestinationTableName per indicare la tabella di destinazione per l'operazione di inserimento bulk.

  5. Chiamare uno dei metodi WriteToServer.

  6. Opzionalmente, aggiornare le proprietà e chiamare WriteToServer di nuovo se necessario.

  7. Chiamare Close o incapsulare le operazioni di copia bulk all'interno di un'istruzione Using.

Attenzione

Usare tipi di dati corrispondenti per le colonne di origine e di destinazione. Se i tipi non corrispondono, SqlBulkCopy tenta di convertire ogni valore di origine nel tipo di dati di destinazione con le regole per Value. Le conversioni possono influire sulle prestazioni e causare errori imprevisti. Ad esempio, la conversione da Double a Decimal può avere esito negativo per alcuni valori.

Esempio

L'applicazione console seguente illustra come caricare i dati con la SqlBulkCopy classe . Nell'esempio viene utilizzato SqlDataReader per copiare dati da Production.Product nel database SQL Server AdventureWorks a una tabella simile nello stesso database.

Importante

Prima di eseguire questo esempio, creare le tabelle di lavoro descritte in Bulk Copy Example Setup. L'esempio illustra la SqlBulkCopy sintassi. Se le tabelle di origine e di destinazione si trovano nella stessa istanza di SQL Server, usare un'istruzione Transact-SQL (T-SQL) INSERT ... SELECT per una copia più veloce.

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

Esecuzione di un'operazione di copia di massa con Transact-SQL e la classe Command

Nell'esempio seguente viene illustrato come usare il ExecuteNonQuery metodo per eseguire l'istruzione BULK INSERT .

Nota

Il percorso del file per l'origine dati è relativo al server. Affinché l'operazione di copia bulk abbia esito positivo, il processo server deve avere accesso a tale percorso.

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();
}

Vedi anche