1. Not so long time ago, I got a report from customer. It's reported that they had a report getted very slow and finally throw an error. I finded fout the problem sql in source code and excuted it in sql managment studio. It costs 1 minute and 46 seconds to run this sql. Indeed, it's quite slowly.
orginal sql:
SELECT distinct case when tblShopPayment.AccountID=0 then 1 else 0 end as Category, tblShopPayment.PaymentID, tblShopPayment.OperatorID, tblShopPayment.AccountID, tblShopPayment.PaymentCreateDate, tblShopPayment.PaymentModeID, tblShopPayment.FlagPaid, tblShopPaymentDetail.ProductName, tblShopPaymentDetail.Quantity, tblShopPaymentDetail.Price, vw_ShopAccountInfo.FirstName, vw_ShopAccountInfo.LastName, tblShopPaymentMode.PaymentModeName FROM tblShopPaymentMode INNER JOIN tblShopPayment INNER JOIN tblShopPaymentDetail ON tblShopPayment.PaymentID = tblShopPaymentDetail.PaymentID ON tblShopPaymentMode.PaymentModeID = tblShopPayment.PaymentModeID INNER JOIN TblShopProduct ON tblShopPaymentDetail.ProductID = TblShopProduct.ProductID INNER JOIN tblShopProductCategory ON TblShopProduct.CategoryID = tblShopProductCategory.ProductCategoryID LEFT OUTER JOIN vw_ShopAccountInfo INNER JOIN tblShopAccount ON vw_ShopAccountInfo.UniqueNo = tblShopAccount.UniqueNo ON tblShopPayment.AccountID = tblShopAccount.AccountID WHERE tblShopPayment.PaymentCreateDate >=convert(datetime,'9.1.2015',104) and tblShopPayment.PaymentCreateDate <=convert(datetime,'10.1.2015',104) and SysTypeID = 3 order by LastName
2. solving the problem
There are 2 solutions to solve the problem.
One way is rebuild the sql , One way is to create index.
I don't want to rebuild the sql. It's so complex and hard to rebuild.
So , I chose to create index.
After creating following indexes, the query reduce to 1 second. Yes, 1s.
--creating following index to improve performance
--creating following index to improve performance --CREATE NONCLUSTERED INDEX [IXZY_tblShopPaymentDetail1] --ON [dbo].[tblShopPaymentDetail] ([PaymentID]) --INCLUDE ([ProductID],[ProductName],[Quantity],[Price]) --CREATE NONCLUSTERED INDEX [IXZY_1Students1] --ON [dbo].[Students] ([Enter_schooltime],[Leave_schooltime]) --INCLUDE ([First_name],[Last_name],[UniqueNo]) --CREATE NONCLUSTERED INDEX [IXZY_1Students12] --ON [dbo].[Students] ([UniqueNo],[Enter_schooltime],[Leave_schooltime]) --INCLUDE ([First_name],[Last_name]) --CREATE NONCLUSTERED INDEX [IXZY_STAFF1] --ON [dbo].[Staff] ([AttendStart],[AttendEnd]) --INCLUDE ([FirstName],[LastName],[UniqueNO]) --CREATE NONCLUSTERED INDEX [IXZY_Staff2] --ON [dbo].[Staff] ([UniqueNO],[AttendStart],[AttendEnd]) --INCLUDE ([FirstName],[LastName]) --CREATE NONCLUSTERED INDEX [IXZY_Parent1] --ON [dbo].[Parent] ([UniqueNo]) --INCLUDE ([FirstName],[LastName],[Family_ID])