This view query is taking 2min to load 500 000 lines.
I’m using EF 4.0 and thread load this view on a DataGrid.
How can I optimize it so it can load in shorter time ?
Update : I updated the query to this and now it takes 55 seconds but still too long !
SELECT ROW_NUMBER() OVER ( ORDER BY ss.IDStore_CardStore DESC ) AS Id_PK ,
SC.IDStockCardIndex ,
SC.Designation ,
ISNULL(P.PMP, 0) PMP ,
ISNULL(SS.Quantity, 0) Quantity ,
SS.UnitePrice * SS.Quantity AS SubTotalStockCard ,
S.StoreName ,
SS.IDPurchaseInvoice
FROM dbo.Stores S
INNER JOIN dbo.StockCardsStores ss ON S.IDStore = ss.IDStore
RIGHT OUTER JOIN dbo.StockCard SC ON ss.IDStockCardIndex = SC.IDStockCardIndex
LEFT OUTER JOIN ( SELECT SUM(UnitePrice * Quantity) / SUM(Quantity) AS PMP ,
IDStockCardIndex
FROM dbo.StockCardsStores AS SCS
GROUP BY IDStockCardIndex
) AS P ON P.IDStockCardIndex = SC.IDStockCardIndex
Use Estimate Execution Plan in SSMS. If you’re using 2008 R2, SSMS will suggest “missing index” that will possibly improve the time overall. 500,000 rows at 55 seconds suggest that one or more table scans are kicking in. The Estimated Execution Plan will identify these. The Plan will also show what part of the query “costs” the most overall, helping you to zero in.
Highlight that inner sub-query and look at the plan for that first. Then work your way outwards.