SQL缓慢插入



我有一个ASP.NET应用程序,它获取一堆存储在XML中的数据集,并将它们扩展到SQL中,在扩展过程中它会执行大量插入。

这些插入需要相当长的时间,现在我公开承认我的SQL技能并不是很好,所以我的诊断方法可能看起来有点粗糙。

在SQL Server管理活动监视器上,处理器时间约为3%,服务器上的实际CPU使用率也在3%左右,因此代码运行不稳定,有0个等待任务,I/O稳定在0.3MB/秒,批处理请求的约为180/秒

在资源等待中,日志记录的等待时间约为900ms,这让我朝着慢磁盘的方向发展,我将日志文件移动到了另一组主轴上,这使我的批处理请求增加到了260/sec,但肯定不会完全停止。

我的想法是对的吗?是磁盘导致了这个盒子的速度变慢,除了新服务器(它是一台带UW320磁盘的旧HP DL385双CPU)之外,所有的东西都在耐心地等待它打开磁盘。有没有办法加快插入速度?

对于SQL Server的大规模插入,您应该真正使用SqlBulkCopy来满足您的需求。

这里有一个小例子。

// Set up your target fields and types
Dictionary<string, string> uploadFields = new Dictionary<string, string>()
{
{ "LocationId", "System.Int32" },
{ "CalendarDate", "System.DateTime" },
{ "IsWorkingDay", "System.Boolean" },
{ "SnapshotDate", "System.DateTime" }
};
// Set up a DataTable to hold the stuff we want to send.
DataTable   massUpdate  = new DataTable();
// Use the dictionary above to set up columns
uploadFields
.Keys
.ToList()
.ForEach(k => massUpdate.Columns.Add(k, Type.GetType(uploadFields[k])));
// Populate your datatable
foreach ( var thing in things )
{
DataRow row = massUpdate.NewRow();
row["LocationId"]       = thing.Id;
row["CalendarDate"]     = thing.Date;
row["IsWorkingDay"]     = thing.IsWorkingDay;
row["SnapshotDate"]     = DateTime.UtcNow;
massUpdate.Rows.Add(row);
}
// Finally, send the contents of the DataTable up via SqlBulkCopy.
// GetConnectionString
using (SqlConnection conn = new SqlConnection("Your connection string"))
{
using (SqlBulkCopy copy = new SqlBulkCopy(conn))
{
conn.Open();
foreach (var key in uploadFields.Keys)
{
copy.ColumnMappings.Add(key, key);
}
// Swap this table name with yoyr own.
copy.DestinationTableName = "DestinationTableName";
copy.WriteToServer(massUpdate);
conn.Close();
}
}

文件:-

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx

不完全熟悉您所处的环境,但交易可能吗?如果是这样的话,您可以通过首先启动一个事务,然后执行一系列INSERT,然后结束事务来大大加快INSERT的速度。否则,每个INSERT都作为自己的事务运行,因此需要进行大量处理才能完成。

最新更新