Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.NET Framework Class Library
SqlBulkCopy Class

Lets you efficiently bulk load a SQL Server table with data from another source.

System..::.Object
  System.Data.SqlClient..::.SqlBulkCopy

Namespace:  System.Data.SqlClient
Assembly:  System.Data (in System.Data.dll)
Visual Basic
Public NotInheritable Class SqlBulkCopy _
    Implements IDisposable
C#
public sealed class SqlBulkCopy : IDisposable
Visual C++
public ref class SqlBulkCopy sealed : IDisposable
F#
[<Sealed>]
type SqlBulkCopy =  
    class
        interface IDisposable
    end

The SqlBulkCopy type exposes the following members.

  NameDescription
Public methodSqlBulkCopy(SqlConnection)Initializes a new instance of the SqlBulkCopy class using the specified open instance of SqlConnection.
Public methodSqlBulkCopy(String)Initializes and opens a new instance of SqlConnection based on the supplied connectionString. The constructor uses the SqlConnection to initialize a new instance of the SqlBulkCopy class.
Public methodSqlBulkCopy(String, SqlBulkCopyOptions)Initializes and opens a new instance of SqlConnection based on the supplied connectionString. The constructor uses that SqlConnection to initialize a new instance of the SqlBulkCopy class. The SqlConnection instance behaves according to options supplied in the copyOptions parameter.
Public methodSqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction)Initializes a new instance of the SqlBulkCopy class using the supplied existing open instance of SqlConnection. The SqlBulkCopy instance behaves according to options supplied in the copyOptions parameter. If a non-null SqlTransaction is supplied, the copy operations will be performed within that transaction.
Top
  NameDescription
Public propertyBatchSizeNumber of rows in each batch. At the end of each batch, the rows in the batch are sent to the server.
Public propertyBulkCopyTimeoutNumber of seconds for the operation to complete before it times out.
Public propertyColumnMappingsReturns a collection of SqlBulkCopyColumnMapping items. Column mappings define the relationships between columns in the data source and columns in the destination.
Public propertyDestinationTableNameName of the destination table on the server.
Public propertyNotifyAfterDefines the number of rows to be processed before generating a notification event.
Top
  NameDescription
Public methodCloseCloses the SqlBulkCopy instance.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodWriteToServer(array<DataRow>[]()[])Copies all rows from the supplied DataRow array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.
Public methodWriteToServer(DataTable)Copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.
Public methodWriteToServer(IDataReader)Copies all rows in the supplied IDataReader to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.
Public methodWriteToServer(DataTable, DataRowState)Copies only rows that match the supplied row state in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.
Top
  NameDescription
Public eventSqlRowsCopiedOccurs every time that the number of rows specified by the NotifyAfter property have been processed.
Top
  NameDescription
Explicit interface implemetationPrivate methodIDisposable..::.DisposeReleases all resources used by the current instance of the SqlBulkCopy class.
Top

Microsoft SQL Server includes a popular command-prompt utility named bcp for moving data from one table to another, whether on a single server or between servers. The SqlBulkCopy class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but SqlBulkCopy offers a significant performance advantage over them.

The SqlBulkCopy class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance.

SqlBulkCopy will fail when bulk loading a DataTable column of type SqlDateTime into a SQL Server column whose type is one of the date/time types added in SQL Server 2008.

The following console application demonstrates how to load data using the SqlBulkCopy class. In this example, a SqlDataReader is used to copy data from the Production.Product table in the SQL Server 2005 AdventureWorks database to a similar table in the same database.

Important noteImportant

This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup (ADO.NET). This code is provided to demonstrate the syntax for using SqlBulkCopy only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data.

Visual Basic
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

            ' 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
        ' 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
C#
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();

            // 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 SqlConnection(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 SqlBulkCopy(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 = 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;";
    }
}

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Biblioteca de clases de .NET Framework
SqlBulkCopy (Clase)

Permite realizar eficazmente una carga masiva de una tabla de SQL Server con datos procedentes de otro origen.

System..::.Object
  System.Data.SqlClient..::.SqlBulkCopy

Espacio de nombres:  System.Data.SqlClient
Ensamblado:  System.Data (en System.Data.dll)
Visual Basic
Public NotInheritable Class SqlBulkCopy _
    Implements IDisposable
C#
public sealed class SqlBulkCopy : IDisposable
Visual C++
public ref class SqlBulkCopy sealed : IDisposable
F#
[<Sealed>]
type SqlBulkCopy =  
    class
        interface IDisposable
    end

El tipo SqlBulkCopy expone los siguientes miembros.

  NombreDescripción
Método públicoSqlBulkCopy(SqlConnection)Inicializa una nueva instancia de la clase SqlBulkCopy utilizando la instancia abierta especificada de SqlConnection.
Método públicoSqlBulkCopy(String)Inicializa y abre una nueva instancia de SqlConnection basándose en el parámetro connectionString proporcionado. El constructor utiliza SqlConnection para inicializar una nueva instancia de la clase SqlBulkCopy.
Método públicoSqlBulkCopy(String, SqlBulkCopyOptions)Inicializa y abre una nueva instancia de SqlConnection basándose en el parámetro connectionString proporcionado. El constructor utiliza esa conexión SqlConnection para inicializar una nueva instancia de la clase SqlBulkCopy. La instancia de SqlConnection se comporta según las opciones proporcionadas en el parámetro copyOptions.
Método públicoSqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction)Inicializa una nueva instancia de la clase SqlBulkCopy utilizando la instancia abierta proporcionada de SqlConnection. La instancia de SqlBulkCopy se comporta según las opciones proporcionadas en el parámetro copyOptions. Si se proporciona una transacción SqlTransaction no nula, las operaciones de copia se realizarán dentro de esa transacción.
Arriba
  NombreDescripción
Propiedad públicaBatchSizeNúmero de filas en cada lote. Al final de cada lote, se envían las filas del lote al servidor.
Propiedad públicaBulkCopyTimeoutNúmero de segundos para que finalice la operación antes de que sobrepase el tiempo de espera.
Propiedad públicaColumnMappingsDevuelve una colección de elementos SqlBulkCopyColumnMapping. Las asignaciones de columnas definen las relaciones entre las columnas del origen de datos y las del destino.
Propiedad públicaDestinationTableNameNombre de la tabla de destino en el servidor.
Propiedad públicaNotifyAfterDefine el número de filas que se va a procesar antes de generarse un evento de notificación.
Arriba
  NombreDescripción
Método públicoCloseCierra la instancia de SqlBulkCopy.
Método públicoEquals(Object)Determina si el objeto Object especificado es igual al objeto Object actual. (Se hereda de Object).
Método protegidoFinalizePermite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por la recolección de elementos no utilizados. (Se hereda de Object).
Método públicoGetHashCodeActúa como función hash para un tipo concreto. (Se hereda de Object).
Método públicoGetTypeObtiene el objeto Type de la instancia actual. (Se hereda de Object).
Método protegidoMemberwiseCloneCrea una copia superficial del objeto Object actual. (Se hereda de Object).
Método públicoToStringDevuelve una cadena que representa el objeto actual. (Se hereda de Object).
Método públicoWriteToServer(array<DataRow>[]()[])Copia todas las filas de la matriz de objetos DataRow proporcionada a una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.
Método públicoWriteToServer(DataTable)Copia todas las filas de la DataTable proporcionada a una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.
Método públicoWriteToServer(IDataReader)Copia todas las filas de la IDataReader proporcionada a una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.
Método públicoWriteToServer(DataTable, DataRowState)Copia sólo las filas que coinciden con el estado de fila proporcionado en la DataTable proporcionada a una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.
Arriba
  NombreDescripción
Evento públicoSqlRowsCopiedSe produce cada vez que se ha procesado el número de filas especificado por la propiedad NotifyAfter.
Arriba
  NombreDescripción
Implementación explícita de interfacesMétodo privadoIDisposable..::.DisposeLibera todos los recursos utilizados por la instancia actual de la clase SqlBulkCopy.
Arriba

Microsoft SQL Server incluye una conocida utilidad de línea de comandos denominada bcp para mover datos de una tabla a otra, ya sea en un solo servidor o entre servidores. La clase SqlBulkCopy permite escribir soluciones de código administrado que proporcionan una funcionalidad similar. Hay otras maneras de cargar datos en una tabla de SQL Server (por ejemplo, instrucciones INSERT), pero el rendimiento de SqlBulkCopy es mucho mayor.

La clase SqlBulkCopy se puede utilizar para escribir datos sólo en tablas de SQL Server. Sin embargo, el origen de datos no se limita a SQL Server; se puede utilizar cualquier origen de datos, siempre que los datos se puedan cargar en una instancia de DataTable o se puedan leer con una instancia de IDataReader.

SqlBulkCopy dará error al hacer una carga masiva de una columna DataTable de tipo SqlDateTime en una columna de SQL Server cuyo tipo es uno de los tipos de fecha y hora agregados en SQL Server 2008.

La siguiente aplicación de consola muestra cómo cargar datos mediante la clase SqlBulkCopy. En este ejemplo, se utiliza SqlDataReader para copiar datos de la tabla Production.Product ubicada en la base de datos AdventureWorks de SQL Server 2005 a una tabla similar en la misma base de datos.

Nota importanteImportante

Este ejemplo no se ejecutará a menos que haya creado las tablas de trabajo como se describe en Configuración de ejemplo de copia masiva (ADO.NET). Este código se proporciona para mostrar cuál debe ser la sintaxis cuando sólo se utiliza SqlBulkCopy. Si las tablas de origen y de destino están en la misma instancia de SQL Server, lo más rápido y sencillo es usar una instrucción INSERT … SELECT de Transact-SQL para copiar los datos.

Visual Basic
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

            ' 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
        ' 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
C#
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();

            // 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 SqlConnection(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 SqlBulkCopy(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 = 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;";
    }
}

.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker