Olg*_*lga 9 database sql-server ado.net identity sqlbulkcopy
我有一个DataTable大约有100,000条记录的ADO.NET .在此表中有一列 xyID没有值,因为该列是IDENTITY在我的SQL Server数据库中自动生成的.
我需要为其他进程检索生成的ID.我正在寻找一种方法来批量复制DataTable到SQL Server数据库,并在相同的"步骤"内"填充"我DataTable生成的ID.
如何使用SqlBulkCopy类检索插入表中的记录的标识值?
我目前正在做这样的事情:
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];
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我们的数据设计支持使用版本 ID 来过滤所有新对象;我们添加的每一行都将具有相同的版本 ID,并且我们之前已删除数据库中已具有此版本 ID 的所有行。
但是,即使有 10 分钟的窗口,我的选择查询当前也在 ExecuteReader 中超时。所以这不是我们最终的解决方案。