我有一个ADO.NET DataTable
,大约有100,000条记录。在此表中有一列xyID
,其中没有值,因为该列是我的SQL Server数据库中自动生成的IDENTITY
。
我需要为其他进程检索生成的ID。我正在寻找一种方法来将此DataTable
批量复制到SQL Server数据库中,并在同一“步骤”内使用生成的ID“填充”我的DataTable
。
如何使用SqlBulkCopy
类检索插入表中的记录的标识值?
答案 0 :(得分:2)
我现在正在做这样的事情:
DataTable objects = new DataTable();
DataColumn keyColumn = new DataColumn("name", typeof(string));
DataColumn versionColumn = new DataColumn("version", typeof(int));
versionColumn.DefaultValue = iVersionID;
objects.Columns.Add(keyColumn);
objects.Columns.Add(versionColumn);
foreach (KeyValuePair<string, NamedObject> kvp in Directory)
{
NamedObject o = kvp.Value;
DataRow row = objects.NewRow();
row[0] = o.Name;
objects.Rows.Add(row);
}
using (SqlBulkCopy updater = new SqlBulkCopy(conn,
SqlBulkCopyOptions.TableLock | SqlBulkCopyOptions.UseInternalTransaction, null))
{
updater.DestinationTableName = "object_table";
updater.WriteToServer(objects);
}
string sQuery = @"SELECT id, name FROM object_table WHERE version = @ver";
using (SqlCommand command = new SqlCommand(sQuery, conn))
{
SqlParameter version = new SqlParameter("@ver", SqlDbType.Int, 4);
version.Value = versionID;
command.Parameters.Add(version);
command.CommandTimeout = 600;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string key = (string)reader[1];
NamedObject item = Directory[key];
item.ID = (int)reader[0];
}
}
}
请注意,我们的数据设计允许使用版本ID过滤所有新对象;我们添加的每一行都具有相同的版本ID,我们之前已经删除了已具有此版本ID的数据库中的所有行。
但是,我的选择查询当前在ExecuteReader中超时,即使是那个10分钟的窗口。所以这不是我们的最终解决方案。