0

The query below performs fairly quickly, however when hit by several visitors at once causes the SQL Server CPU to spike greatly. How would you rewrite this query to reduce the impact?

SELECT     *
FROM         (SELECT     TOP 1 a.adID, a.type, a.position, a.image, a.altText, a.caption, a.link, isNull(v.viewCount, 0) AS viewCount
                       FROM          bannerAds a LEFT OUTER JOIN
                                                  (SELECT     adID, count(viewID) AS viewCount
                                                    FROM          bannerAdsViews
                                                    WHERE      viewDateTime IS NOT NULL AND DateDiff(day, viewDateTime, GetDate()) = 0
                                                    GROUP BY adID) v ON a.adID = v.adID
                       WHERE      a.startDate <= getDate() AND a.endDate >= getDate() AND a.position = 1 AND type = 'standard'
                       ORDER BY viewCount) pos1
UNION ALL
SELECT     *
FROM         (SELECT     TOP 1 a.adID, a.type, a.position, a.image, a.altText, a.caption, a.link, isNull(v.viewCount, 0) AS viewCount
                       FROM          bannerAds a LEFT OUTER JOIN
                                                  (SELECT     adID, count(viewID) AS viewCount
                                                    FROM          bannerAdsViews
                                                    WHERE      viewDateTime IS NOT NULL AND DateDiff(day, viewDateTime, GetDate()) = 0
                                                    GROUP BY adID) v ON a.adID = v.adID
                       WHERE      a.startDate <= getDate() AND a.endDate >= getDate() AND a.position = 2 AND type = 'standard'
                       ORDER BY viewCount) pos2
2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by BitBlt
0

Could be any number of things causing it. Not knowing your table structures or your data volumes, I can only recommend generic things to try, such as:
1. Are your tables indexed? If not, you might try indexing them.
2. Are your tables volatile? As in, lots of random inserts/updates? If so, you might consider updating statistics or reorg-ing frequently.
3. You might consider putting it in a stored procedure, and using a local variable to store the results of GetDate(), then use that in your query.
4. If you decide to go the stored procedure route, you might also consider using a temp table to store the results of your subselect (since it's used in both parts of the union) and then join to that.

Sorry I can't be more specific than that. If I knew more about your table structures and data, I might take a swing at trying to rewrite the query altogether. Since I don't... well, you get the picture.

Good luck!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.