开发者

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

This question already has answers here: Dynamic SELECT TOP @var In SQL Server (6 answers) Closed 7 years ago.开发者_运维技巧
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)?


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

select top (@top) * from tablename


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


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 :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜