Dynamic SELECT TOP @var In SQL Server

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

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


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)


SELECT TOP (@count) * FROM SomeTable

This will only work with SQL 2005+