SqlBulkCopy.DestinationTableName SqlBulkCopy.DestinationTableName SqlBulkCopy.DestinationTableName SqlBulkCopy.DestinationTableName Property

Definição

Nome da tabela de destino no servidor.Name of the destination table on the server.

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 da propriedade

O valor da cadeia de caracteres da propriedade DestinationTableName ou null se nenhum tiver sido aplicado.The string value of the DestinationTableName property, or null if none as been supplied.

Exemplos

O aplicativo de console a seguir demonstra como carregar dados em massa usando uma conexão que já está aberta.The following console application demonstrates how to bulk load data using a connection that is already open. A tabela de destino é uma tabela no banco de dados AdventureWorks .The destination table is a table in the AdventureWorks database.

Neste exemplo, a conexão é usada primeiro para ler dados de uma tabela SQL Server para uma SqlDataReader instância do.In this example, the connection is first used to read data from a SQL Server table to a SqlDataReader instance. Os dados de origem não precisam estar localizados em SQL Server; Você pode usar qualquer fonte de dados que possa ser lida em IDataReader um ou carregada em DataTableum.The source data does not have to be located on SQL Server; you can use any data source that can be read to an IDataReader or loaded to a DataTable.

Importante

Este exemplo não será executado a menos que você tenha criado as tabelas de trabalho conforme descrito em configuração de exemplo de cópia em massa.This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. Esse código é fornecido para demonstrar a sintaxe somente para uso de SqlBulkCopy .This code is provided to demonstrate the syntax for using SqlBulkCopy only. Se as tabelas de origem e destino estiverem na mesma instância de SQL Server, será mais fácil e rápido usar uma instrução Transact- INSERT … SELECT SQL para copiar os dados.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.

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;";
    }
}
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

Comentários

Se DestinationTableName não tiver sido definido quando WriteToServer for chamado, um ArgumentNullException será lançado.If DestinationTableName has not been set when WriteToServer is called, an ArgumentNullException is thrown.

Se DestinationTableName for modificado enquanto uma WriteToServer operação estiver em execução, a alteração não afetará a operação atual.If DestinationTableName is modified while a WriteToServer operation is running, the change does not affect the current operation. O novo DestinationTableName valor será usado na próxima vez que WriteToServer um método for chamado.The new DestinationTableName value is used the next time a WriteToServer method is called.

DestinationTableNameé um nome de três partes (<database>.<owningschema>.<name>).DestinationTableName is a three-part name (<database>.<owningschema>.<name>). Você pode qualificar o nome da tabela com seu banco de dados e o esquema de propriedade se escolher.You can qualify the table name with its database and owning schema if you choose. No entanto, se o nome da tabela usar um sublinhado ("") ou qualquer outro caractere especial, você deverá escapar do nome usando colchetes[<database>.<owningschema>.<name_01>]ao redor como em ().However, if the table name uses an underscore ("") or any other special characters, you must escape the name using surrounding brackets as in ([<database>.<owningschema>.<name_01>]). Para obter mais informações, consulte identificadores de banco de dados.For more information, see Database Identifiers.

Você pode copiar dados em massa para uma tabela temporária usando um valor como tempdb..#table ou tempdb.<owner>.#table para a DestinationTableName propriedade.You can bulk-copy data to a temporary table by using a value such as tempdb..#table or tempdb.<owner>.#table for the DestinationTableName property.

Aplica-se a

Veja também