Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Slow running cross apply

Author  Topic 

bcanonica
Starting Member

35 Posts

Posted - 2009-11-25 : 09:09:57
Below I am trying to return the top address for each customer in a one to many relationship with the customeraddresses table. I used a cross apply to solve this issue, but the query is running incredibly slow. 12 minutes for 8,000 records. I ran an execution plan and I get three index seek (nonclusterd) customeraddresses table that are the majority of the cost. Can I fix with indexes or should I rewrite the query in a more efficient manner? If I have to rewrite what direction should I take?

	WITH PreferredAddresses as 
(
SELECT c.CustomerID, AddressID
FROM Customers c OUTER APPLY
(SELECT TOP 1 *
FROM CustomerAddresses a
WHERE a.CustomerID = c.CustomerID
ORDER BY AddressTypeID, AddressID
) a
)
SELECT c.*, a.AddressID, a.AddressTypeID, OrganizationName,
AddressLine1, AddressLine2, AddressLine3, City, a.StateProvinceID,
ZipCode, Honorarium, StateProvinceAbbrev, TypeName
FROM

bcanonica
Starting Member

35 Posts

Posted - 2009-11-25 : 10:42:44
Ok I figured it out hope this helps someone else out.


WITH PrimaryAddresses as
(

SELECT
DISTINCT c.CustomerID
, (SELECT TOP 1 AddressID
FROM CustomerAddresses ca
WHERE ca.CustomerID=c.CustomerID
ORDER BY AddressTypeID ASC, AddressID DESC) as AddressID
FROM Customers c )
SELECT pa.CustomerID
, pa.AddressID
, ca.AddressTypeID
, at.TypeName
, OrganizationName
, AddressLine1
, AddressLine2
, AddressLine3
, City
, ca.StateProvinceID
, s.StateProvinceAbbrev
, ZipCode
FROM PrimaryAddresses pa
LEFT JOIN CustomerAddresses ca ON pa.AddressID=ca.AddressID
LEFT JOIN AddressTypes at on ca.AddressTypeID=at.AddressTypeID
LEFT JOIN StateProvinces s on ca.StateProvinceID=s.StateProvinceID
WHERE pa.AddressID IS NOT NULL
Go to Top of Page
   

- Advertisement -