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 @variable 1

Status
Not open for further replies.

wooody1245

Programmer
Sep 13, 2005
28
US
Is there a way that I can use a variable in a select top statement like the one below?
select top @max_results from my_table where column1 = @variable

I'm passing @max_results to a stored procedure to limit the number of rows returned.
 
You can build up the SELECT statement in a varchar variable and then EXEC it:

Code:
CREATE PROCEDURE GetMaxResults
@Variable int,
@Max_results int
AS
DECLARE @SQL varchar(500)
set @sql = 'select top ' + CAST(@Max_results as varchar(10) + ' * FROM WHERE column1 = ' + cast(@Variable as varchar(10))
EXEC (@SQL)


Bob Boffin
 
You can also set the ROWCOUNT setting using the variable. Setting the ROWCOUNT setting has the same basic effect as using TOP without the overhead of using synamic SQL.
Code:
Create Procedure p1
   @max_results int
as
set ROWCOUNT @max_results
select *
from table
go

Denny
MCSA (2003) / MCDBA (SQL 2000)

--Anything is possible. All it takes is a little research. (Me)
[noevil]
 
the code posted by BBOFIN is better and simpler... applause!
 
I belive Denny's code is much better and more readable and maintainable...

Jim
 
My 2 cents

There are arguments for both, I normally avoid using dynamic SQL for issues which have been debated here previously, though MrDenny's option can have problems if you dont remember to reset the rowcount, or if in the SELECT statement you have subselect statements or derived queries in functions, which the rowcount is then applied to them.

In answer to what you are doing, based on the actual question I would use MrDenny's answer!

"I'm living so far beyond my income that we may almost be said to be living apart
 
Fortunately for us SQL Server 2005 allows a variable for the top statement but until then I would use mrdenny's code with the addition of setting rowcount to 0 at the bottom



“I sense many useless updates in you... Useless updates lead to defragmentation... Defragmentation leads to downtime...Downtime leads to suffering..Defragmentation is the path to the darkside.. DBCC INDEXDEFRAG and DBCC DBREINDEX are the force...May the force be with you" --
 
I used bboffin's solution, but if I had it to do again I would use mrdenny's solution. It took me a while to get the string formatted properly. Thanks for the suggestions!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top