Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 How do I use variables with 'top'?

Author  Topic 

KidSQL
Yak Posting Veteran

88 Posts

Posted - 2005-08-17 : 15:55:12
Hi,

I have a statement I've been using as follows:

select top 1000 score from mytable

but I need to vary how many I'm going to fetch from this table, so I've introduced a variable called @topcount. When I try to do this, however:

select top @topcount score from mytable

I get the error message:

Incorrect syntax near '@topcount'

Can anyone show me the correct way to do this?

Any help would be much appreciated.

Thanks!

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2005-08-17 : 15:57:17
Always check the articles first before posting. I typed in SELECT TOP and found this article:
http://www.sqlteam.com/item.asp?ItemID=233

Tara
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2005-08-17 : 15:57:49
SET @sql = 'SELECT TOP ' + @topcount + ' score FROM myTable'
EXEC(@sql)


Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx
Go to Top of Page

KidSQL
Yak Posting Veteran

88 Posts

Posted - 2005-08-17 : 16:05:22
Thank you.
Go to Top of Page

ScottRoss
Starting Member

1 Post

Posted - 2005-08-18 : 17:19:39
I've been using that method (creating a string of the text). I have tons of different tables, and want to execute the same function/procs on them, and call the table name itself as a parameter.

However, it's a pain to debug.... there's isn't a better way to do this? It seems like such a workaround....
Go to Top of Page
   

- Advertisement -