gpt4 book ai didi

c# - SqlBulkCopy ColumnMapping 错误

转载 作者:行者123 更新时间:2023-12-03 07:53:46 24 4
gpt4 key购买 nike

我的目标是将通用表从一个数据库复制到另一个数据库。我想让它按原样复制数据,如果有新列,可以删除表中的任何内容或添加新列。我唯一可能想要更改的是添加一些版本控制,这可以在查询的单独部分中完成。

打开数据没有问题,但是当我尝试批量复制时却失败了。我浏览了几篇文章,最接近的是这个: SqlBulkCopy Insert with Identity Column

我从我的代码中删除了 SqlBulkCopyOptions.KeepIdentity 但它仍然在抛出

“给定的 ColumnMapping 与源或目标中的任何列都不匹配”错误

我试过使用 SqlBulkCopyOptions,但到目前为止运气不好。

想法?

public void BatchBulkCopy(string connectionString, DataTable dataTable, string DestinationTbl, int batchSize)
{
// Get the DataTable
DataTable dtInsertRows = dataTable;

using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString))
{
sbc.DestinationTableName = DestinationTbl;

// Number of records to be processed in one go
sbc.BatchSize = batchSize;

// Finally write to server
sbc.WriteToServer(dtInsertRows);
}
}

最佳答案

如果我可以建议另一种方法,我会看看 SMO (SQL Server Management Objects) 库来执行此类任务。你可以找到一篇有趣的文章here .使用 SMO,您可以在 SQL Server 中执行任务,例如批量复制,将表、列和数据库视为对象。

前段时间,我在自己开发的一个小型开源应用程序中使用了SMO,名为SQLServerDatabaseCopy。 .为了将数据从一个表复制到另一个表,我创建了这段代码(完整代码是 here ):

foreach (Table table in Tables)
{
string columnsTable = GetListOfColumnsOfTable(table);

string bulkCopyStatement = "SELECT {3} FROM [{0}].[{1}].[{2}]";
bulkCopyStatement = String.Format(bulkCopyStatement, SourceDatabase.Name, table.Schema, table.Name, columnsTable);

using (SqlCommand selectCommand = new SqlCommand(bulkCopyStatement, connection))
{
LogFileManager.WriteToLogFile(bulkCopyStatement);
SqlDataReader dataReader = selectCommand.ExecuteReader();

using (SqlConnection destinationDatabaseConnection = new SqlConnection(destDatabaseConnString))
{
if (destinationDatabaseConnection.State == System.Data.ConnectionState.Closed)
{
destinationDatabaseConnection.Open();
}

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationDatabaseConnection))
{
bulkCopy.DestinationTableName = String.Format("[{0}].[{1}]", table.Schema, table.Name);

foreach (Column column in table.Columns)
{
//it's not needed to perfom a mapping for computed columns!
if (!column.Computed)
{
bulkCopy.ColumnMappings.Add(column.Name, column.Name);
}
}

try
{
bulkCopy.WriteToServer(dataReader);
LogFileManager.WriteToLogFile(String.Format("Bulk copy successful for table [{0}].[{1}]", table.Schema, table.Name));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
finally
{
//closing reader
dataReader.Close();
}
}
}
}
}

如您所见,您必须将 ColumnMappings 添加到每一列的 BulkCopy 对象,因为您必须定义源表的哪一列必须映射到目标表的一列。这就是您出现以下错误的原因:The given ColumnMapping does not match up with any column in the source or destination

关于c# - SqlBulkCopy ColumnMapping 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22039959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com