gpt4 book ai didi

c# - 跳过 SqlBulkCopy 中的某些列

转载 作者:太空狗 更新时间:2023-10-29 17:29:54 26 4
gpt4 key购买 nike

我正在对两个具有不同列集的 SQL Server 2008 使用 SqlBulkCopy(将一些数据从 prod 服务器移动到 dev ).所以想跳过一些尚不存在/尚未删除的列。

我该怎么做? ColumnMappings 有什么技巧吗?

编辑:

我接下来要做的是:

DataTable table = new DataTable();
using (var adapter = new SqlDataAdapter(sourceCommand))
{
adapter.Fill(table);
}

table.Columns
.OfType<DataColumn>()
.ForEach(c => bulk.ColumnMappings.Add(
new SqlBulkCopyColumnMapping(c.ColumnName, c.ColumnName)));

bulk.WriteToServer(table)

并得到:

The given ColumnMapping does not match up with any column in the source or destination.

最佳答案

DataTable table = new DataTable();
using (var adapter = new SqlDataAdapter(sourceCommand))
{
adapter.Fill(table);
}

using (SqlBulkCopy bulk = new SqlBulkCopy(targetConnection, SqlBulkCopyOptions.KeepIdentity, null) { DestinationTableName = tableName })
{
foreach (string columnName in GetMapping(stringSource, stringTarget, tableName))
{
bulk.ColumnMappings.Add(new SqlBulkCopyColumnMapping(columnName, columnName));
}

targetConnection.Open();
bulk.WriteToServer(table);
}

private static IEnumerable<string> GetMapping(string stringSource, string stringTarget, string tableName)
{
return Enumerable.Intersect(
GetSchema(stringSource, tableName),
GetSchema(stringTarget, tableName),
StringComparer.Ordinal); // or StringComparer.OrdinalIgnoreCase
}

private static IEnumerable<string> GetSchema(string connectionString, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "sp_Columns";
command.CommandType = CommandType.StoredProcedure;

command.Parameters.Add("@table_name", SqlDbType.NVarChar, 384).Value = tableName;

connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return (string)reader["column_name"];
}
}
}
}

关于c# - 跳过 SqlBulkCopy 中的某些列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3784930/

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