Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

select top N with order by, N is dynamic

Status
Not open for further replies.

agar

Programmer
Jun 6, 2001
19
US
Hi all,

Does anybody know of an easy way to select the top N records of a table, where the select uses an order by clause, and N is dynamic (for example, is passed as a parameter to the stored procedure)? The "SELECT TOP" syntax must be hardcoded, and "SET ROWCOUNT" unfortunately limits the number of rows before the rows are sorted in an "order by". I have been doing it with a while loop, using "SELECT TOP 1" each time, but I'd like to employ a more elegant and less complex solution, if one exists. I could construct the entire query dynamically use "sp_executesql", but I wonder if this would prevent SQL Server from caching the execution plan.
 
Try building the command string by concatenating the command with the N (as a char type), then execute the finished string with sp_executesql. Robert Bradley
Sr. DBA, some big company
cheap prints and oil paintings:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top