Dynamic SELECT TOP @var In SQL Server

SqlSql Server-2005

Sql Problem Overview


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

Sql Solutions


Solution 1 - Sql

SELECT TOP (@count) * FROM SomeTable

This will only work with SQL 2005+

Solution 2 - Sql

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)

Solution 3 - Sql

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

Solution 4 - Sql

Or you just put the variable in parenthesis

DECLARE @top INT = 10;

SELECT TOP (@Top) *
FROM <table_name>;

Solution 5 - Sql

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

Solution 6 - Sql

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)

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
QuestioneddiegrovesView Question on Stackoverflow
Solution 1 - SqlBrian KimView Answer on Stackoverflow
Solution 2 - Sqlx0nView Answer on Stackoverflow
Solution 3 - SqlCodewerksView Answer on Stackoverflow
Solution 4 - SqlShawnThompsonView Answer on Stackoverflow
Solution 5 - SqlDavid CastroView Answer on Stackoverflow
Solution 6 - SqlJanView Answer on Stackoverflow