I have the following view containing a 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
Which when I run it using WHERE ObjectKey = 1234
returns a result instantly. When I use this query in a join though:
Select *
from tblPerson p
inner join
vwPhoneNumberByPref ph on p.PersonID = ph.ObjectKey
it takes about 10 seconds and in the execution plan, is doing a sort on over 200,000 rows.
When not used in a join, it is doing the "sort" on a single row. I tried doing the join using CROSS APPLY
which makes it marginally faster, but still takes too long and is still sorting 200,000 odd rows.
How can I improve the performance?
Additional Info:
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
There is an index on tblPhoneNumber
on ObjectTypeName, ObjectKey, Preference, isDeleted
The function dbo.ApplyMask
applies the Mask from PhoneType to PhoneNumber, the mask is (##) #### ####
I am not actually running Select * from tblPerson
, But even running SELECT PersonID from tblPerson INNER JOIN ....
causes the query to take ages. This was just for example.