MattNorman
Well-known member
- Joined
- May 22, 2021
- Messages
- 98
- Programming Experience
- 1-3
I am trying to improve the speed of a query that pulls data for a report.
For some reason the query I have written works perfectly fine in SQL Management Studio and returns the expected data.
If I run it from my app it does not return any data.
I have tried the following:
For some reason the query I have written works perfectly fine in SQL Management Studio and returns the expected data.
If I run it from my app it does not return any data.
I have tried the following:
- Wrap query in a transaction
- Tried using a global temporary table instead of local
- Tried executing query to create temp table and then separate query to get data
C#:
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlDataReader dr;
// Create command.
var cmd = new SqlCommand("", connection, transaction);
query += $@"
CREATE TABLE #CallerIDs
(
[CallerID] NVARCHAR(50)
)
INSERT INTO #CallerIDs ([CallerID])
SELECT [CallerID]
FROM [ApexCCM].[dbo].[HistoricalCallDetailData]
WHERE Date >= @StartDate
AND Date <= @EndDate
AND [Time] >= @StartTime
AND [Time] <= @EndTime
AND LEN(CallerID) > 5
AND LEFT(CallerID, 1) <> 'T'
";
if (filters.Skills.Count > 0) { query += ("AND [SkillName1] IN (@Skills)"); }
query += $@"
GROUP BY [CallerID]
HAVING COUNT(*) > 1
";
query += $@"
SELECT h.[RecordID], h.[Date], h.[Time], h.[CallerID], h.[DispositionName], h.[SkillName1]
FROM [ApexCCM].[dbo].[HistoricalCallDetailData] h
JOIN #CallerIDs c ON h.[CallerID] = c.[CallerID]
WHERE h.[Date] >= @StartDate
AND h.[Date] <= @EndDate
AND h.[Time] >= @StartTime
AND h.[Time] <= @EndTime
";
query += $@"
DROP TABLE #CallerIDs
";
// Parameters.
_ = cmd.Parameters.AddWithValue("@StartDate", DateTime.Parse(filters.StartDate));
_ = cmd.Parameters.AddWithValue("@EndDate", DateTime.Parse(filters.EndDate));
_ = cmd.Parameters.AddWithValue("@StartTime", CMSTimeFromTimeSpan(filters.StartTime));
_ = cmd.Parameters.AddWithValue("@EndTime", CMSTimeFromTimeSpan(filters.EndTime));
// Skill name parameters.
string selectedSkillNames = string.Join(",", filters.Skills.Where(a => a.IsChecked).Select(a => $"'{a.SkillName}'"));
if (!string.IsNullOrEmpty(selectedSkillNames))
{
_ = cmd.Parameters.AddWithValue("@Skills", selectedSkillNames);
}
// Update command text.
cmd.CommandText = query;
Console.Write(query);
// Get data.
dr = cmd.ExecuteReader();
returnData = GetCallDetailRepeatCallersModelListFromDataReader(dr);
dr.Close();
// Get policy matches.
_ = Parallel.ForEach(returnData, model =>
{
model.MatchedPolicies = DataManagerPolicyLookup.GetPolicyMatches(model.CallerID);
});
transaction.Commit();
}