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
Release: 2025-01-10 08:42:41
Original
132 people have browsed it

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
Copy after login

To achieve the desired functionality, use the following syntax:

SELECT TOP (@count) * FROM SomeTable
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template