using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace SqlRunMultipleQueriesInParallel
{
class Program
{
private static readonly string connectionString = new SqlConnectionStringBuilder { IntegratedSecurity = true, MultipleActiveResultSets = true }.ConnectionString;
const string query = "SELECT R.* FROM REPORTS.Analytics.dbo.Resume AS R INNER JOIN REPORTS.Analytics.dbo.ResumeExtra AS RE ON R.Id = RE.ResumeId AND RE.IsModerated = 1 AND RE.IsModeratedRubric = 1 WHERE R.State = 1 AND R.IsProfessional = 1";
const int limit = 20000;
const int threads = 4;
private static int[] stats;
private static void Main(string[] args)
{
var timer = new Stopwatch();
timer.Start();
stats = new int[threads];
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
Parallel.For(0, threads, i =>
{
using (var command = new SqlCommand(string.Format("{0} ORDER BY Id OFFSET {1} ROWS FETCH NEXT {2} ROWS ONLY", query, i * limit, limit), connection) { CommandTimeout = 0 })
{
using (var reader = command.ExecuteReader())
{
if (reader.HasRows)
{
var current = 0;
while (reader.Read())
{
stats[i] += 1;
Console.Write("{0}\r", string.Join(", ", stats.Select(num => string.Format("{0:N0}", num))));
}
}
reader.Close();
}
}
});
connection.Close();
}
Console.WriteLine("\nDone in {0:g}", timer.Elapsed);
Console.ReadLine();
}
}
}