“Streaming”从SQL Server中的表中读取超过1000万行

以流方式(如SQL Server Management Studio)从表(在SQL Server 2012,BI实例中)读取数百万条记录的最佳策略是什么?

我需要在本地缓存这些记录(C#控制台应用程序)以进行进一步处理。

更新 – 与SqlDataReader一起使用的示例代码

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; using System.Threading; namespace ReadMillionsOfRows { class Program { static ManualResetEvent done = new ManualResetEvent(false); static void Main(string[] args) { Process(); done.WaitOne(); } public static async Task Process() { string connString = @"Server=;Database=;User Id=;Password=;Asynchronous Processing=True"; string sql = "Select * from tab_abc"; using (SqlConnection conn = new SqlConnection(connString)) { await conn.OpenAsync(); using (SqlCommand comm = new SqlCommand(sql)) { comm.Connection = conn; comm.CommandType = CommandType.Text; using (SqlDataReader reader = await comm.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { //process it here } } } } done.Set(); } } } 

使用SqlDataReader它只是前进和快速。 它只会在读取记录范围时保留对记录的引用。

这取决于缓存的外观。 如果您要将所有内容存储在内存中,并且DataSet适合作为缓存,则只需读取DataSet中的所有内容即可。

如果没有,请按照上面的建议使用SqlDataReader ,逐个读取记录,将它们存储在大缓存中。

但请注意,对于大型数据库表 – 您的数据库,已经有一种非常流行的缓存机制。 使用正确的索引配置,数据库可能会胜过您的缓存。

您可以使用Entity Framework并使用TakeSkip对select进行分页, Take通过缓冲区获取行。 如果您需要在内存缓存中使用这么大的数据集,我建议使用GC.GetTotalMemory来测试是否还有剩余空闲内存。