How do I return a row number or place of a record in a sql table?
Posted on 2007-11-14
I run an ASP.NET website with a monthly contest. Members can enter 1 script for each contest. Scripts can then be voted on.
There are three relevant SQL tables:
Contest with the field: ContestID
Script with the fields: ContestID, ScriptID, and Title
ScriptComment with the fields: ScriptID and Score
Scripts are grouped by contest and come in place (first, second, third, etc.) based on the average of all the scores they received.
I need a QUICK stored procedure that will accept ScriptID as a parameter and return back the place that script came in, in that particular contest.
Currently, I get this information by creating a virtual table and populating it with joined data from Script and ScriptComment. I order the table by average Score desc. I then use a select statement against that table using the ScriptID and return back the row number. This works, but it is very slow. There are times where I might need to list 300 scripts and I need to do this lookup for each script to display what place they came in.
I need a much faster way to get the place of any script in a contest. I think the Virtual Table is killing the speed. I have been trying to find a solution using a view or the new SQL 2005 command Row_Number(), but I have been unsuccessful.
If anyone has a speedy solution, I would love to hear it.
Thanks a lot,