SqlBulkCopyColumnMappingCollection.Remove(SqlBulkCopyColumnMapping) Método
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Remove o elemento SqlBulkCopyColumnMapping especificado do SqlBulkCopyColumnMappingCollection.
public:
void Remove(System::Data::SqlClient::SqlBulkCopyColumnMapping ^ value);
public void Remove (System.Data.SqlClient.SqlBulkCopyColumnMapping value);
member this.Remove : System.Data.SqlClient.SqlBulkCopyColumnMapping -> unit
Public Sub Remove (value As SqlBulkCopyColumnMapping)
Parâmetros
- value
- SqlBulkCopyColumnMapping
O objeto SqlBulkCopyColumnMapping a ser removido da coleção.
Exemplos
O exemplo a seguir executa duas operações de cópia em massa. A primeira operação copia informações de cabeçalho do pedido de vendas e a segunda copia os detalhes do pedido de vendas. Embora não seja estritamente necessário neste exemplo (porque as posições ordinais das colunas de origem e destino correspondem), o exemplo define mapeamentos de coluna para cada operação de cópia em massa. Ambas as cópias em massa incluem um mapeamento para SalesOrderID, portanto, em vez de limpar toda a coleção entre operações de cópia em massa, o exemplo remove todos os mapeamentos, exceto o mapeamento SalesOrderID e adiciona os mapeamentos apropriados para a segunda operação de cópia em massa.
Importante
Essa amostra não será executada, a menos que você tenha criado as tabelas de trabalho conforme descrito em Configuração de exemplo de cópia em massa. Esse código é fornecido para demonstrar a sintaxe para usar somente SqlBulkCopy. Se as tabelas de origem e destino estiverem na mesma instância SQL Server, será mais fácil e rápido usar uma instrução Transact-SQL INSERT ... SELECT
para copiar os dados.
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a connection to the AdventureWorks database.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
// Empty the destination tables.
SqlCommand deleteHeader = new SqlCommand(
"DELETE FROM dbo.BulkCopyDemoOrderHeader;",
connection);
deleteHeader.ExecuteNonQuery();
SqlCommand deleteDetail = new SqlCommand(
"DELETE FROM dbo.BulkCopyDemoOrderDetail;",
connection);
deleteDetail.ExecuteNonQuery();
// Perform an initial count on the destination
// table with matching columns.
SqlCommand countRowHeader = new SqlCommand(
"SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;",
connection);
long countStartHeader = System.Convert.ToInt32(
countRowHeader.ExecuteScalar());
Console.WriteLine(
"Starting row count for Header table = {0}",
countStartHeader);
// Perform an initial count on the destination
// table with different column positions.
SqlCommand countRowDetail = new SqlCommand(
"SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;",
connection);
long countStartDetail = System.Convert.ToInt32(
countRowDetail.ExecuteScalar());
Console.WriteLine(
"Starting row count for Detail table = {0}",
countStartDetail);
// Get data from the source table as a SqlDataReader.
// The Sales.SalesOrderHeader and Sales.SalesOrderDetail
// tables are quite large and could easily cause a timeout
// if all data from the tables is added to the destination.
// To keep the example simple and quick, a parameter is
// used to select only orders for a particular account
// as the source for the bulk insert.
SqlCommand headerData = new SqlCommand(
"SELECT [SalesOrderID], [OrderDate], " +
"[AccountNumber] FROM [Sales].[SalesOrderHeader] " +
"WHERE [AccountNumber] = @accountNumber;",
connection);
SqlParameter parameterAccount = new SqlParameter();
parameterAccount.ParameterName = "@accountNumber";
parameterAccount.SqlDbType = SqlDbType.NVarChar;
parameterAccount.Direction = ParameterDirection.Input;
parameterAccount.Value = "10-4020-000034";
headerData.Parameters.Add(parameterAccount);
SqlDataReader readerHeader = headerData.ExecuteReader();
// Get the Detail data in a separate connection.
using (SqlConnection connection2 = new SqlConnection(connectionString))
{
connection2.Open();
SqlCommand sourceDetailData = new SqlCommand(
"SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " +
"[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " +
"INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." +
"[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " +
"WHERE [AccountNumber] = @accountNumber;", connection2);
SqlParameter accountDetail = new SqlParameter();
accountDetail.ParameterName = "@accountNumber";
accountDetail.SqlDbType = SqlDbType.NVarChar;
accountDetail.Direction = ParameterDirection.Input;
accountDetail.Value = "10-4020-000034";
sourceDetailData.Parameters.Add(accountDetail);
SqlDataReader readerDetail = sourceDetailData.ExecuteReader();
// Create the SqlBulkCopy object.
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(connectionString))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoOrderHeader";
// Guarantee that columns are mapped correctly by
// defining the column mappings for the order.
bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID");
// Define SqlBulkCopyColumnMapping objects so they
// can be referenced later.
SqlBulkCopyColumnMapping columnMappingDate =
bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate");
SqlBulkCopyColumnMapping columnMappingAccount =
bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber");
// Write readerHeader to the destination.
try
{
bulkCopy.WriteToServer(readerHeader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
readerHeader.Close();
}
// Set up the order details destination.
bulkCopy.DestinationTableName ="dbo.BulkCopyDemoOrderDetail";
// Rather than clearing mappings that are not necessary
// for the next bulk copyo peration, the unneeded mappings
// are removed with the Remove method.
bulkCopy.ColumnMappings.Remove(columnMappingDate);
bulkCopy.ColumnMappings.Remove(columnMappingAccount);
// Add order detail column mappings.
bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID");
bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty");
bulkCopy.ColumnMappings.Add("ProductID", "ProductID");
bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice");
bulkCopy.WriteToServer(readerDetail);
// Write readerDetail to the destination.
try
{
bulkCopy.WriteToServer(readerDetail);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
readerDetail.Close();
}
}
// Perform a final count on the destination
// tables to see how many rows were added.
long countEndHeader = System.Convert.ToInt32(
countRowHeader.ExecuteScalar());
Console.WriteLine("{0} rows were added to the Header table.",
countEndHeader - countStartHeader);
long countEndDetail = System.Convert.ToInt32(
countRowDetail.ExecuteScalar());
Console.WriteLine("{0} rows were added to the Detail table.",
countEndDetail - countStartDetail);
Console.WriteLine("Press Enter to finish.");
Console.ReadLine();
}
}
}
private static string GetConnectionString()
// To avoid storing the connection 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 connection As SqlConnection = New SqlConnection(connectionString)
connection.Open()
' Empty the destination tables.
Dim deleteHeader As New SqlCommand( _
"DELETE FROM dbo.BulkCopyDemoOrderHeader;", connection)
deleteHeader.ExecuteNonQuery()
deleteHeader.Dispose()
Dim deleteDetail As New SqlCommand( _
"DELETE FROM dbo.BulkCopyDemoOrderDetail;", connection)
deleteDetail.ExecuteNonQuery()
' Perform an initial count on the destination table
' with matching columns.
Dim countRowHeader As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;", _
connection)
Dim countStartHeader As Long = System.Convert.ToInt32( _
countRowHeader.ExecuteScalar())
Console.WriteLine("Starting row count for Header table = {0}", _
countStartHeader)
' Perform an initial count on the destination table
' with different column positions.
Dim countRowDetail As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;", _
connection)
Dim countStartDetail As Long = System.Convert.ToInt32( _
countRowDetail.ExecuteScalar())
Console.WriteLine("Starting row count for Detail table = " & _
countStartDetail)
' Get data from the source table as a SqlDataReader.
' The Sales.SalesOrderHeader and Sales.SalesOrderDetail
' tables are quite large and could easily cause a timeout
' if all data from the tables is added to the destination.
' To keep the example simple and quick, a parameter is
' used to select only orders for a particular account as
' the source for the bulk insert.
Dim headerData As SqlCommand = New SqlCommand( _
"SELECT [SalesOrderID], [OrderDate], " & _
"[AccountNumber] FROM [Sales].[SalesOrderHeader] " & _
"WHERE [AccountNumber] = @accountNumber;", _
connection)
Dim parameterAccount As SqlParameter = New SqlParameter()
parameterAccount.ParameterName = "@accountNumber"
parameterAccount.SqlDbType = SqlDbType.NVarChar
parameterAccount.Direction = ParameterDirection.Input
parameterAccount.Value = "10-4020-000034"
headerData.Parameters.Add(parameterAccount)
Dim readerHeader As SqlDataReader = _
headerData.ExecuteReader()
' Get the Detail data in a separate connection.
Using connection2 As SqlConnection = New SqlConnection(connectionString)
connection2.Open()
Dim sourceDetailData As SqlCommand = New SqlCommand( _
"SELECT [Sales].[SalesOrderDetail].[SalesOrderID], " & _
"[SalesOrderDetailID], [OrderQty], [ProductID], [UnitPrice] " & _
"FROM [Sales].[SalesOrderDetail] INNER JOIN " & _
"[Sales].[SalesOrderHeader] " & _
"ON [Sales].[SalesOrderDetail].[SalesOrderID] = " & _
"[Sales].[SalesOrderHeader].[SalesOrderID] " & _
"WHERE [AccountNumber] = @accountNumber;", connection2)
Dim accountDetail As SqlParameter = New SqlParameter()
accountDetail.ParameterName = "@accountNumber"
accountDetail.SqlDbType = SqlDbType.NVarChar
accountDetail.Direction = ParameterDirection.Input
accountDetail.Value = "10-4020-000034"
sourceDetailData.Parameters.Add( _
accountDetail)
Dim readerDetail As SqlDataReader = _
sourceDetailData.ExecuteReader()
' Create the SqlBulkCopy object.
Using bulkCopy As SqlBulkCopy = _
New SqlBulkCopy(connectionString)
bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderHeader"
' Guarantee that columns are mapped correctly by
' defining the column mappings for the order.
bulkCopy.ColumnMappings.Add("SalesOrderID", "SalesOrderID")
' Define SqlBulkCopyColumnMapping objects so they
' can be referenced later.
Dim columnMappingDate As SqlBulkCopyColumnMapping = _
bulkCopy.ColumnMappings.Add("OrderDate", "OrderDate")
Dim columnMappingAccount As SqlBulkCopyColumnMapping = _
bulkCopy.ColumnMappings.Add("AccountNumber", "AccountNumber")
' Write readerHeader to the destination.
Try
bulkCopy.WriteToServer(readerHeader)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
readerHeader.Close()
End Try
' Set up the order details destination.
bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail"
' Rather than clearing mappings that are not necessary
' for the next bulk copy operation, the unneeded
' mappings are removed with the Remove method.
bulkCopy.ColumnMappings.Remove(columnMappingDate)
bulkCopy.ColumnMappings.Remove(columnMappingAccount)
' Add order detail column mappings.
bulkCopy.ColumnMappings.Add("SalesOrderDetailID", "SalesOrderDetailID")
bulkCopy.ColumnMappings.Add("OrderQty", "OrderQty")
bulkCopy.ColumnMappings.Add("ProductID", "ProductID")
bulkCopy.ColumnMappings.Add("UnitPrice", "UnitPrice")
' Write readerDetail to the destination.
Try
bulkCopy.WriteToServer(readerDetail)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
readerDetail.Close()
End Try
End Using
' Perform a final count on the destination tables
' to see how many rows were added.
Dim countEndHeader As Long = System.Convert.ToInt32( _
countRowHeader.ExecuteScalar())
Console.WriteLine("{0} rows were added to the Header table.", _
countEndHeader - countStartHeader)
Dim countEndDetail As Long = System.Convert.ToInt32( _
countRowDetail.ExecuteScalar())
Console.WriteLine("{0} rows were added to the Detail table.", _
countEndDetail - countStartDetail)
Console.WriteLine("Press Enter to finish.")
Console.ReadLine()
End Using
End Using
End Sub
Private Function GetConnectionString() As String
' To avoid storing the connection 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
O Remove método é mais comumente usado quando você usa uma única SqlBulkCopy instância para processar mais de uma operação de cópia em massa. Se você criar mapeamentos de coluna para uma operação de cópia em massa, deverá remover mapeamentos que não se aplicam mais depois que o WriteToServer método for chamado e antes de definir o mapeamento para a próxima cópia em massa. Você pode limpar toda a coleção usando o Clear método ou remover mapeamentos individualmente usando o Remove método ou o RemoveAt método .
Executar várias cópias em massa usando a mesma SqlBulkCopy instância geralmente será mais eficiente do ponto de vista de desempenho do que usar um separado SqlBulkCopy para cada operação.