Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic SELECT TOP @var In SQL Server

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 
like image 739
eddiegroves Avatar asked Oct 06 '08 20:10

eddiegroves


People also ask

What is select top 100 percent SQL Server?

TOP (100) PERCENT is completely meaningless in recent versions of SQL Server, and it (along with the corresponding ORDER BY, in the case of a view definition or derived table) is ignored by the query processor. You're correct that once upon a time, it could be used as a trick, but even then it wasn't reliable.

Can I use CTE in dynamic SQL?

They allow to encapsulate the SQL query and reuse result recursively as a data source in the main query or in another CTE within one statement. In this article I'll illustrate how to use CTEs using an example of dynamic query which counts records from one table joined with second table used to limit the result set.


1 Answers

SELECT TOP (@count) * FROM SomeTable 

This will only work with SQL 2005+

like image 169
Brian Kim Avatar answered Sep 17 '22 18:09

Brian Kim