Friday, March 09, 2007

How do I use a variable in a TOP clause in SQL Server?

http://sqlserver2000.databases.aspfaq.com/how-do-i-use-a-variable-in-a-top-clause-in-sql-server.html

I have a web page that runs a script which is so slow that it will time out if the number of records is too great. The temporary solution is to split the records into two subsets and then process those sets seperately. Doing that manually was not too big of a deal, but I wanted a better way.

I calculate the number of rows / 2.
Then I needed to use that value to automatically split the set. The only thing I needed to change was the brackets around the variable. So it turned out to be this:

Select top (@myvar) from mytable.

The article goes way more into depth

No comments: