如何防止查询超时?

时间:2017-04-17 09:30:19

标签: sql sql-server tsql sql-server-2012

SELECT C.CompanyName,
       B.BranchName, 
       E.EmployerName,
       FE.EmployeeUniqueID,
       pcr.EmployerUniqueID, 
       Case when FE.Status_id= 1 then 1 else 0 end IsUnPaid, 
       Case when re.EmployeeUniqueID IS NULL OR re.EmployeeUniqueID= '' then 0 else 1 end AS 'EmployeeRegistration',
       FE.IncomeFixedComponent,
       FE.IncomeVariableComponent, 
       Convert(varchar(11), Fe.PayStartDate, 106) as PayStartDate,
       Convert(varchar(11), Fe.PayEndDate, 106) as PayEndDate,
       S.StatusDescription, 
       FE.IsRejected, 
       FE.ID 'EdrID',   
       Convert(varchar(20), tr.TransactionDateTime, 113) as TransactionDateTime, 
       tr.BatchNo, 
       tr.IsDIFCreated, 
       Convert(varchar(20),tr.DIFFileCreationDateTime,113) as DiffDateTime
    From File_EdrEntries FE 
    JOIN PAFFiles pe ON pe.ID = FE.PAFFile_ID
    inner Join RegisteredEmployees RE
    ON RE.EmployeeUniqueID= FE.EmployeeUniqueID
    inner join File_PCREntries pcr on pe.ID=pcr.PAFFile_ID 
    JOIN Employers E ON E.EmployerID = pcr.EmployerUniqueID
    JOIN Branches B ON B.BranchID = E.Branch_ID 
    JOIN companies C ON C.COMPANYID = B.COMPANY_ID  
    JOIN Statuses S ON S.StatusID = FE.Status_ID
    JOIN Transactions tr on tr.EDRRecord_ID= fe.ID
    where  E.Branch_id=3
    AND FE.IsRejected=0 AND FE.Status_id= 3 and tr.BatchNo is not null
    AND Re.Employer_ID= re.Employer_ID;

这个查询应该返回1000万或更多的记录,并且由于没有大量的记录,它通常会导致超时。那么我怎样才能改善它的表现,因为我已经尽力而为。

2 个答案:

答案 0 :(得分:2)

首先,您需要

  1. 优化查询更多
  2. required Indexes添加到查询中涉及的表
  3. 然后,

    您可以使用它来增加查询超时:

    SET LOCK_TIMEOUT 1800;  
    SELECT @@LOCK_TIMEOUT AS [Lock Timeout];
    

    另请参阅This Post

答案 1 :(得分:0)

找出哪些表组合过滤了大多数数据。例如,如果以下查询筛选出大部分数据,您可以考虑使用所需数据创建临时表,将其编入索引,然后在较大的查询中使用该数据。

SELECT fe.*,re.*    
From File_EdrEntries FE 
    inner Join RegisteredEmployees RE
    ON RE.EmployeeUniqueID= FE.EmployeeUniqueID

将查询分成较小的块可能是最好的方法。还要确保你有适当的索引