2011-11-28 442 views
0

我只是想知道如果任何人都可以提供任何建議,以改善我的查詢。LINQ到SQL - 慢查詢

基本上,它會將2行合併到1中。唯一不同的行是'類型'字符列('S'或'C')和值。我想要做的是用'S'值和'C'值選擇一行,並計算差值(S-C)。

我的查詢很有用,但速度很慢 - 大約需要8秒才能得到結果,這對我的應用程序來說並不理想。我希望我可以改變數據庫結構,但我不能傷心!

這裏是我的查詢:

var sales = (from cm in dc.ConsignmentMarginBreakdowns 
      join sl in dc.SageAccounts on new { LegacyID = cm.Customer, Customer = true } equals new { LegacyID = sl.LegacyID, Customer = sl.Customer } 
      join ss in dc.SageAccounts on sl.ParentAccount equals ss.ID 
      join vt in dc.VehicleTypes on cm.ConsignmentTripBreakdown.VehicleType.Trim() equals vt.ID.ToString() into vtg 
      where cm.ConsignmentTripBreakdown.DeliveryDate >= dates.FromDate && cm.ConsignmentTripBreakdown.DeliveryDate <= dates.ToDate 
      where (customer == null || ss.SageID == customer) 
      where cm.BreakdownType == 'S' 
      orderby cm.Depot, cm.TripNumber 
      select new 
      { 
       NTConsignment = cm.NTConsignment, 
       Trip = cm.ConsignmentTripBreakdown, 
       LegacyID = cm.LegacyID, 
       Costs = dc.ConsignmentMarginBreakdowns.Where(a => a.BreakdownType == 'C' && a.NTConsignment == cm.NTConsignment && a.LegacyID == cm.LegacyID && a.TripDate == cm.TripDate && a.Depot == cm.Depot && a.TripNumber == cm.TripNumber).Single().Value, 
       Sales = cm.Value ?? 0.00m, 
       Customer = cm.Customer, 
       SageID = ss.SageID, 
       CustomerName = ss.ShortName, 
       FullCustomerName = ss.Name, 
       Vehicle = cm.ConsignmentTripBreakdown.Vehicle ?? "None", 
       VehicleType = vtg.FirstOrDefault().VehicleTypeDescription ?? "Subcontractor" 
      }); 

回答

1

當優化Linq到SQL查詢時,一個好的開始是SQL Server Profiler。在那裏你可以找到Linq to SQL生成的SQL代碼。從那裏,你可以玩弄linq查詢,看看你是否可以寫出更好的查詢。如果這不起作用,你可以隨時手動編寫一個存儲過程,然後從Linq調用它到SQL。

1

真的是沒有提供作出明智的意見的足夠信息。例如,每個表中有多少行?生成的T-SQL看起來像什麼?

我首先建議的一件事就是拿出輸出的T-SQL,生成查詢計劃並查找表或索引掃描。