How can I decrease the execution time with this sql squery? it is taking over a minute to execute and return rows.(executed in Sql server management studio 2008)
if(@NotInvoiced =1)
BEGIN
Select @Command =
'select Distinct C.FileID, C.FileName, convert(nvarchar,C.DateReported,111) AS ''DateReported'',
C.FileDetailsPlainText, CFIT.Level3 as ''InvestigationType'', INV.FName + '' '' + INV.LName AS ''Name'',
convert(nvarchar,DD,111) AS ''DD'', i.FirstName + '' '' + i.LastName AS ''ReportedBy''
from CaseFiles C
join InvestigatorCaseFileAccess IA on C.FileID=IA.CaseFileID
LEFT OUTER JOIN CaseFileTimeBills tb on C.FileID=tb.FileID
LEFT OUTER JOIN CaseFileExpenses e on C.FileID=e.FileID
left join Element07a_Persons i on i.PersonID = c.PersonID
LEFT OUTER JOIN CaseFileInvestigationTypes CFIT ON C.InvestigationTypeID = CFIT.InvestigationTypeID
LEFT OUTER JOIN Investigators INV ON C.InvestigatorID = INV.InvestigatorID
where (tb.InvNumber IS null OR e.InvNumber IS null) and Deleted=0 and IA.InvestigatorID=' + CONVERT (nvarchar(max),@InvestigatorID) + ' and IA.AllowAccess = ''True''
and tb.FileID = C.FileID or e.FileID=C.FileID '
END
As we discovered in the comments, it looks like your problem was that you were missing parentheses around
tb.FileID = C.FileID or e.FileID=C.FileID.Adding those parentheses fundamentally changes the filtering semantics and therefore changes the data you get back. It’s like your original query without the parentheses was returning gobs of data, or at the very least comparing every single possible row when it only needed to compare a few.
Marlin Pierce made the good observation that parenthesizing those ORs allows the DBMS to use utilize indices (for example for the condition
Deleted=0), whereas before it could not.