Home > Database > Mysql Tutorial > How Can I Efficiently Select a Large Number of Rows in SQL Server?

How Can I Efficiently Select a Large Number of Rows in SQL Server?

Patricia Arquette
Release: 2024-12-31 20:29:14
Original
991 people have browsed it

How Can I Efficiently Select a Large Number of Rows in SQL Server?

Selecting Rows in SQL Server

The provided query fails to return more than 7374 rows because it exhausts the number of rows in the sys.columns table. To overcome this limitation, a more efficient approach is to use cascaded CTEs to generate a "Tally Table" or "Numbers Table".

Here's an optimized query using cascaded CTEs:

DECLARE @Range AS INT = 7374

;WITH E1(N) AS( -- 10 ^ 1 = 10 rows
    SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N)
),
E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), -- 10 ^ 2 = 100 rows
E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b), -- 10 ^ 4 = 10,000 rows
E8(N) AS(SELECT 1 FROM E4 a CROSS JOIN E4 b), -- 10 ^ 8 = 10,000,000 rows
CteTally(N) AS(
    SELECT TOP(@Range) ROW_NUMBER() OVER(ORDER BY(SELECT NULL))
    FROM E8
)
SELECT * FROM CteTally
Copy after login

This approach is incredibly efficient because it generates zero reads and scales to extremely large numbers of rows. For performance comparisons and more information on Tally Tables, refer to the linked resources provided in the response.

The above is the detailed content of How Can I Efficiently Select a Large Number of Rows 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