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
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.
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.
SELECT TOP (@count) * FROM SomeTable
This will only work with SQL 2005+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With