c# - 数据库表的低内存遍历

标签 c# performance sql-server-2008

我有一个数据库,其中包含大量带有日期/时间戳记的记录。我需要遍历这些记录(按时间顺序)并对它们进行一些分析。

数据库太大,一次拉不下每条记录,所以我想一次拉几个星期/天/小时/等等。我遇到的问题是,无论我尝试过什么,数据库 (SQL Server) 都会使用我机器上的所有内存。即使在应用程序关闭后,sqlservr.exe 仍在使用我的所有内存。它通常使用大约 1.8 GB 的内存,无论我的“批处理”仅包含 10 条记录还是 1,000,000 条记录。

问题是:我怎样才能一次查询数据库以获取“成批”记录,而不让数据库消耗每一点内存?

我正在使用 System.Data.SqlClient 库。这是一些伪代码:

String file = "C:\\db.mdf";
String connString = @"Data Source=.\SQLExpress;AttachDbFilename="C:\db.mdf";Integrated Security=True;User Instance=True";

SqlConnection conn = new SqlConnection(connString);
conn.Open();

DateTime start = DateTime.MinValue;
DateTime end = DateTime.MaxValue;

while()
{
   // This should query for 1 hour at a time (but I should be able to change the time interval)
   // I would like for the memory usage to be proportional to the time interval

   String query = "SELECT * From MyTable WHERE Date BETWEEN '" + start.ToString() + "' AND '" + end.ToString() + "'";
   SqlCommand cmd = new SqlCommand(query, conn);
   SqlDataReader reader = command.ExecuteReader();

   while(reader.Read())
      ProcessRecord(ref reader);

   start = end;
   end = end.AddHours(1);
}

conn.Close();

C#
.NET 3.5
SQL 服务器 2008

谢谢。

最佳答案

这是正常的,SQL Server 将使用所有可用内存unless configured differently .

当您的其他应用程序请求更多内存时,Sql Server Express 将释放内存,但它会尝试使用所有可能的内存来缓存查询计划和数据。

引用链接文章:

The following example sets the max server memory option to 4 GB:

 exec sp_configure 'show advanced options', 1; 
 GO 
 RECONFIGURE; 
 GO
 exec sp_configure 'max server memory', 4096; 
 GO 
 RECONFIGURE; 
 GO
 exec sp_configure 'show advanced options', 0;
 RECONFIGURE;  
 GO 

请注意SqlConnectionSqlCommandSqlDataReader 实现了IDisposable,所以您通常希望将它们包装在 using 子句中。

关于c# - 数据库表的低内存遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9789486/

相关文章:

c# - MVVM 异常处理

c# - 如何在不违反单一职责原则的情况下编写类似的测试用例?

c# - 正则表达式可以从字符串中提取多个数字吗?

nhibernate - 为什么 ROW_NUMBER OVER(ORDER BY 列)返回的结果顺序与仅 ORDER BY 列不同?

c# - Fluent NHibernate 一对一映射

python - Django QuerySet 上的计数与 len

c++ - C++ 中的 Fast(est) 可变堆实现

java - 在 Java 中缩放数组的最有效方法?

sql - 在 SQL 的 UPDATE 语句中混合 IF 语句

sql-server - SQL Server : IsCharAlpha