370

How can I have a dynamic variable setting the amount of rows to return in SQL Server? Below is not valid syntax in SQL Server 2005+:

DECLARE @count int
SET @count = 20

SELECT TOP @count * FROM SomeTable
Brian Kim
  • 24,916
  • 6
  • 38
  • 26
Eddie Groves
  • 33,851
  • 14
  • 47
  • 48

6 Answers6

671
SELECT TOP (@count) * FROM SomeTable

This will only work with SQL 2005+

Brian Kim
  • 24,916
  • 6
  • 38
  • 26
43

The syntax "select top (@var) ..." only works in SQL SERVER 2005+. For SQL 2000, you can do:

set rowcount @top

select * from sometable

set rowcount 0 

Hope this helps

Oisin.

(edited to replace @@rowcount with rowcount - thanks augustlights)

x0n
  • 51,312
  • 7
  • 89
  • 111
  • 2
    I've heard that it is possible to get incorrect row number with @@RowCount if you have multi-column primary key. Is that true? – Brian Kim Oct 06 '08 at 20:40
14

In x0n's example, it should be:

SET ROWCOUNT @top

SELECT * from sometable

SET ROWCOUNT 0

http://msdn.microsoft.com/en-us/library/ms188774.aspx

Codewerks
  • 5,884
  • 5
  • 29
  • 33
8
declare @rows int = 10

select top (@rows) *
from Employees
order by 1 desc -- optional to get the last records using the first column of the table
David Castro
  • 1,773
  • 21
  • 21
6

Or you just put the variable in parenthesis

DECLARE @top INT = 10;

SELECT TOP (@Top) *
FROM <table_name>;
Evaldas Buinauskas
  • 13,739
  • 11
  • 55
  • 107
ShawnThompson
  • 61
  • 1
  • 1
4

Its also possible to use dynamic SQL and execute it with the exec command:

declare @sql  nvarchar(200), @count int
set @count = 10
set @sql = N'select top ' + cast(@count as nvarchar(4)) + ' * from table'
exec (@sql)
Jan
  • 15,802
  • 5
  • 35
  • 59
  • 12
    But be (very) wary of [SQL injection attacks](https://en.wikipedia.org/wiki/SQL_injection) with this approach – MadSkunk Nov 23 '15 at 11:05