CTE Index recommendations on multiple keyed table

时光怂恿深爱的人放手 提交于 2019-12-12 04:13:54

问题


I have a View which is keyed on both ChargeID and CustomerID (Charge can be split between multiple customers). The View consists of 2 tables (heavily simplified here, actual tables have ~40 columns each):

CREATE TABLE tblCharge (ChargeID int NOT NULL, ParentChargeID int)
CREATE TABLE tblChargeShare (ChargeShareID int NOT NULL, ChargeID int NOT NULL, CustomerID int, TotalAmount money, TaxAmount money, DiscountAmount money)

The View just joins these both together:

CREATE VIEW vwBASEChargeChargeShareCustomer AS
Select ParentChargeID, b.* from tblCharge a inner join tblChargeShare b on a.ChargeID = b.ChargeID

I then have a CTE for getting the subcharges for the parent:

WITH RCTE AS
(
SELECT  ParentChargeId, ChargeID, 1 AS Lvl, ISNULL(TotalAmount, 0) as TotalAmount,  ISNULL(TaxAmount, 0) as TaxAmount,  
ISNULL(DiscountAmount, 0) as DiscountAmount, CustomerID, ChargeID as MasterChargeID
FROM vwBASEChargeChargeShareCustomer Where ParentChargeID is NULL

UNION ALL

SELECT rh.ParentChargeID, rh.ChargeID, Lvl+1 AS Lvl, ISNULL(rh.TotalAmount, 0),  ISNULL(rh.TaxAmount, 0),  ISNULL(rh.DiscountAmount, 0) , rh.CustomerID 
, rc.MasterChargeID 
FROM vwBASEChargeChargeShareCustomer rh
INNER JOIN RCTE rc ON rh.PArentChargeID = rc.ChargeID and rh.CustomerID = rc.CustomerID )

Select MasterChargeID, CustomerID, ParentChargeID, ChargeID, TotalAmount, TaxAmount, DiscountAmount , Lvl
FROM  RCTE r 

So the CTE is joining on CustomerID and ChargeID=ParentChargeID

This works well, but does not perform well on large data sets (millions of Charges).

What is the best way to Index the tables (or view) to get the best performance? (SQL 2008R2 and above)

来源:https://stackoverflow.com/questions/22802484/cte-index-recommendations-on-multiple-keyed-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!