views:

132

answers:

1

Hello!

I have an SQL Query like this:

SELECT TOP (@TopType) AdvertID, IsAdvertImage, AdvertData
FROM Adverts
WHERE AdvertSize = @AdvertSize
ORDER BY NEWID()

Each row in the table Adverts also has a column called Views, is it possible to also increase views with 1 for the banners that has been fetched? So I set TopType to 4 and get 4 banners, these banners have their views increased with 1 so that I can keep track of how many times a banner has been displayed.

+3  A: 
WITH cte AS (
 SELECT TOP (@TopType) 
 AdvertID, IsAdvertImage, AdvertData, Views
 FROM Adverts
 WHERE AdvertSize = @AdvertSize
 ORDER BY NEWID())
UPDATE cte 
 SET Views = Views + 1
OUTPUT INSERTED.AdvertID
 , INSERTED.IsAdvertImage
 , INSERTED.AdvertData;

But ORDER BY NEWID() is going to perform horrible. Even with TOP (1) still has to scan the entire table, spool the selected columns in tempdb, sort, the take TOP from that. And is also going to be an update conflict bonanza between the Views = Views + 1 X-lock and the full scan S-locks...

Remus Rusanu
I am stuck, what is the best solution to solve this problem? Without having to worry about the S-lock. This Select statement is inside a stored procedure, so i can modify it. The important part is that it sends x random adverts back to the caller.
Patrick
I don't get it. If you can't modify the stored proc, why do you ask to select *and* update *in the same statement*?
Remus Rusanu
Why does the update have to happen in the same statement? I built an ad server several years back, and the recording of the stats was fairly quick, but this should never interrupt the "pulling" of the banners. We would record the "view" not by the select from the table but by a hit to a landing page, recording it to a log file which was consumed later. It can be handled offline because the increase of views by 1 does not have to happen simultaneously... especially since you are just pulling random banners anyway, why does it have to be updated right away?
Aaron Bertrand
@Aaron: from all the problems I had to troubleshoot over the past few years, probably the most prevalent was 'contention caused by hit counter update' :)
Remus Rusanu
"I don't get it. If you can't modify the stored proc, why do you ask to select and update in the same statement? – Remus Rusanu 3 hours ago" Sorry for the confusion, it's my stored procedure. I can update it however i want.
Patrick
Aaron Bertrand - Its not that important that it get's updated straight away. Its more an informal info so that we have some knowledge of how many views a certain banner gets. If i were to log the banner hits to a log file i would be forced to setup a windows schedule that reads the log file once a day and add the records to the database. I was just trying to be lacy and get everything done at the same time. It's not that important if it causes to much hustle.
Patrick