T-SQL – 1 million records in 1 second

I thought this is worth noting. This is the way to generate 1 million records within 1 second in SQL Server 2005. I'll have the code pasted here so that I can have a reference the next time I need to use it. As Namwar Rizvi said, this code is proposed in SQL Server 2005 TSQL Querying by Microsoft press.

--Declare a variable to hold the
--count of rows to be generated

Declare @p_NumberOfRows Bigint

--We need 1 million rows

Select @p_NumberOfRows=100000;

With Base As
(
Select 1 as n
Union All
Select n+1 From Base Where n < Ceiling(SQRT(@p_NumberOfRows))
),
Expand As
(
Select 1 as C
From Base as B1, Base as B2
),
Nums As
(
Select Row_Number() OVER(ORDER BY C) As n
From Expand
)
Select n from Nums Where n<=@p_NumberOfRows

--Remove Maximum Recursion level constraint

OPTION (MaxRecursion 0);

This article is part of the GWB Archives. Original Author: Nestor

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.