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 MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

"Select Top" not working with a variable

Status
Not open for further replies.

pradipto

Programmer
Apr 29, 2002
22
US
Suppose I have a function/procedure where I need to select the Top n rows where the value of n is based by a variable, how I do it.

For instance, the following is NOT working:

Select Top @Num MyValue
From MyTable
Where <some condition>

Any suggestions will be very helpful ...

Thanks.
 
I believe this should work

Code:
declare @tsql varchar(8000)
SET @tsql = 'SELECT TOP ' + @num + 'MyValue FROM mytable where ...'

EXEC(@tsql)
 
correction


Code:
declare @tsql varchar(8000)
SET @tsql = 'SELECT TOP ' + [blue]cast(@num as varchar(10))[/blue] + 'MyValue FROM mytable where ...'

EXEC(@tsql)
 
You need an Order By clause and prefably on a column that is unique.
Code:
[Blue]SET[/Blue] [Black]RowCount[/Black] @Top
[Blue]SELECT[/Blue] [Gray]*[/Gray] [Blue]FROM[/Blue] YourTable [Blue]ORDER[/Blue] [Blue]BY[/Blue] YourOrderColumn
-Karl

[red] Cursors, triggers, user-defined functions and dynamic SQL are an axis of evil![/red]
[green]Life's uncertain...eat dessert first...www.deerfieldbakery.com[/green]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top