关于多个键控表的CTE索引建议

时间:2014-04-02 05:44:32

标签: sql sql-server sql-server-2008-r2 common-table-expression

我有一个关于ChargeID和CustomerID的视图(可以在多个客户之间分配费用)。视图由2个表组成(这里大大简化了,实际表每个有~40列):

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)

View只是将它们加在一起:

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

然后我有一个CTE来获得父母的补贴:

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 

因此,CTE正在加入CustomerID和ChargeID = ParentChargeID

这种方法效果很好,但在大型数据集上却表现不佳(数百万次收费)。

索引表(或视图)以获得最佳性能的最佳方法是什么? (SQL 2008R2及以上版本)

0 个答案:

没有答案