2

我有以下包含 PIVOT 的视图:

CREATE VIEW [vwPhoneNumberByPref]
AS
SELECT * FROM(
    SELECT ObjectKey, ObjectTypeName,r_id,MaskedNumber FROM (
        SELECT * ,ROW_NUMBER() OVER (PARTITION BY ObjectKey, ObjectTypeName ORDER BY preference) as r_id
        FROM vwPhoneNumberMasked  ) AS a WHERE r_id<=3
    )AS P
PIVOT(
    MAX(MaskedNumber) FOR r_id in ([1],[2],[3])
)AS Pvt

当我使用它运行它时,它会WHERE ObjectKey = 1234立即返回结果。当我在连接中使用此查询时:

Select * 
from tblPerson p 
inner join 
    vwPhoneNumberByPref ph on p.PersonID = ph.ObjectKey

它大约需要 10 秒,在执行计划中,正在对超过 200,000 行进行排序。

当不用于连接时,它会在单行上进行“排序”。我尝试使用CROSS APPLY它进行连接,使其速度稍快,但仍然需要很长时间并且仍在对 200,000 奇数行进行排序。

我怎样才能提高性能?


附加信息:

CREATE VIEW [vwPhoneNumberMasked] AS
SELECT ph.ObjectTypeName, ph.ObjectKey, dbo.ApplyMask(ph.PhoneNumber, pt.Mask), ph.Preference
FROM tblPhoneNumber ph inner join tblPhoneType pt on
ph.PhoneTypeName = pt.Name
WHERE ph.isDeleted = 0
GO

CREATE TABLE tblPhoneType
Name varchar(20) NOT NULL,
Mask varchar(20) NOT NULL
GO

tblPhoneNumber上有一个索引ObjectTypeName, ObjectKey, Preference, isDeleted

该函数dbo.ApplyMask将 PhoneType 中的掩码应用于 PhoneNumber,掩码为(##) #### ####

我实际上并没有运行Select * from tblPerson,但即使运行也会SELECT PersonID from tblPerson INNER JOIN ....导致查询花费很长时间。这只是一个例子。

4

1 回答 1

0

在您提供更多信息后,我建议您尝试关注。在表上tblPhoneNumber添加索引:

create index ix_tblPhoneNumber_1
    on tblPhoneNumber (isDeleted, ObjectKey, ObjectTypeName, Preference)
        include (PhoneNumber, PhoneTypeName)

在桌子上tblPhoneType添加(如果没有)

create unique clustered index ix_tblPhoneType
    on tblPhoneType (PhoneTypeName)

或者

create unique index ix_tblPhoneType
    on tblPhoneType (PhoneTypeName) include (Mask)

将您的视图更改vwPhoneNumberMasked为:

ALTER VIEW [vwPhoneNumberMasked] AS
SELECT ph.ObjectTypeName, ph.ObjectKey, mp.Value as MaskedNumber, ph.Preference
FROM tblPhoneNumber ph
    inner /*loop*/ join tblPhoneType pt on ph.PhoneTypeName = pt.Name
    cross apply ftMaskPhone(ph.PhoneNumber, pt.Mask) mp
WHERE ph.isDeleted = 0

这个答案ftMaskPhone的答案在哪里(请使用方法 2版本)。

于 2013-08-13T20:04:08.530 回答