Home >Database >Mysql Tutorial >How Can I Use a Variable to Dynamically Set the Number of Rows Returned by SELECT TOP in SQL Server?

How Can I Use a Variable to Dynamically Set the Number of Rows Returned by SELECT TOP in SQL Server?

Barbara Streisand
Barbara StreisandOriginal
2025-01-10 08:42:41134browse

How Can I Use a Variable to Dynamically Set the Number of Rows Returned by SELECT TOP in SQL Server?

Dynamic SELECT TOP @var in SQL Server

In SQL Server, it is often desirable to have a dynamic variable determine the number of rows returned by a query. Unfortunately, the following syntax is not valid in SQL Server 2005 and later:

DECLARE @count int
SET @count = 20

SELECT TOP @count * FROM SomeTable

To achieve the desired functionality, use the following syntax:

SELECT TOP (@count) * FROM SomeTable

This syntax dynamically determines the number of rows to return based on the value of the @count variable. It is supported in SQL Server 2005 and later.

The above is the detailed content of How Can I Use a Variable to Dynamically Set the Number of Rows Returned by SELECT TOP in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn