Use variable with TOP in select statement in SQL Server without making it dynamic

SqlSql ServerSql Server-2005Tsql

Sql Problem Overview


declare @top  int
set @top = 5
select top @top * from tablename

Is it possible?

Or any idea for such a logic (i don't want to use dynamic query)?

Sql Solutions


Solution 1 - Sql

Yes, in SQL Server 2005 it's possible to use a variable in the top clause.

select top (@top) * from tablename

Solution 2 - Sql

SQL Server 2005 actually allows us to parameterize the TOP clause, using a variable, expression or statement. So you can do things like:

SELECT TOP (@foo) a FROM table ORDER BY a 
 
SELECT TOP (SELECT COUNT(*) FROM somewhere else) a FROM table ORDER BY a 
 
SELECT TOP (@foo + 5 * 4 / 2) a FROM table ORDER BY a 

Source

Solution 3 - Sql

In 2005 and later, you can do it as there are several replies in this thread.

Whats less known is that you can achieve this also in 2k, by using SET ROWCOUNT.

  -- Works in all versions
  SELECT TOP 10
 
  -- Does not work on 2000
  SELECT TOP (10)
  SELECT TOP (@rows)
 
  -- Works in both 2ooo and 2oo5
  SET ROWCOUNT @max
 
  SELECT * 
  FROM ...
 
  SET ROWCOUNT 0

Note, if you forget the SET ROWCOUNT 0 at the end, the limit persists.. and you will end up with very hard to locate bugs :-)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPareshView Question on Stackoverflow
Solution 1 - SqlGuffaView Answer on Stackoverflow
Solution 2 - SqlEspoView Answer on Stackoverflow
Solution 3 - SqlBrimstedtView Answer on Stackoverflow