Compartir a través de


SqlBulkCopy.DestinationTableName Propiedad

Definición

Nombre de la tabla de destino en el servidor.

public:
 property System::String ^ DestinationTableName { System::String ^ get(); void set(System::String ^ value); };
public string DestinationTableName { get; set; }
member this.DestinationTableName : string with get, set
Public Property DestinationTableName As String

Valor de propiedad

El valor de cadena de la propiedad DestinationTableName o null si no se ha proporcionado ningún valor.

Ejemplos

La siguiente aplicación de consola muestra cómo cargar datos de forma masiva mediante una conexión que ya está abierta. La tabla de destino es una tabla de la base de datos AdventureWorks .

En este ejemplo, la conexión se usa primero para leer datos de una tabla de SQL Server a una SqlDataReader instancia de . Los datos de origen no tienen que encontrarse en SQL Server; puede usar cualquier origen de datos que se pueda leer en o IDataReader cargar en .DataTable

Importante

Este ejemplo no se ejecuta a menos que haya creado las tablas de trabajo como se describe en Configuración de ejemplos de copia masiva. Este código se proporciona para mostrar la sintaxis para usar SqlBulkCopy. Si las tablas de origen y destino están en la misma instancia de SQL Server, es más fácil y rápido usar una instrucción Transact-SQL INSERT … SELECT para copiar los datos.

using Microsoft.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;";
    }
}

Comentarios

Si DestinationTableName no se ha establecido cuando WriteToServer se llama a , se produce una ArgumentNullException excepción . Si DestinationTableName se modifica mientras se ejecuta una WriteToServer operación, el cambio no afecta a la operación actual. El nuevo DestinationTableName valor se usa la próxima vez que se llame a un WriteToServer método .

DestinationTableName es un nombre de tres partes (<database>.<owningschema>.<name>). Si quiere, puede calificar el nombre de tabla con su base de datos y esquema propietario. Sin embargo, si el nombre de la tabla usa un carácter de subrayado ("_") o cualquier otro carácter especial, debe escapar el nombre con corchetes circundantes como en ([<database>.<owningschema>.<name_01>]).

Puede copiar datos de forma masiva en una tabla temporal mediante un valor como tempdb..#table o tempdb.<owner>.#table para la DestinationTableName propiedad .

Se aplica a