Last active
September 10, 2022 01:41
-
-
Save JerryNixon/24f37d4fc16ede0ef0acfc08808f5688 to your computer and use it in GitHub Desktop.
Generate an arbitrary range in T-SQL UDF.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DBCC DROPCLEANBUFFERS; | |
CHECKPOINT; | |
DBCC FREEPROCCACHE WITH no_infomsgs; | |
GO | |
CREATE OR ALTER FUNCTION Range (@start BIGINT, @end BIGINT) | |
RETURNS @table TABLE (Id BIGINT) AS | |
BEGIN | |
-- Jerry Nixon | |
DECLARE @sqr BIGINT = SQRT(SQRT(SQRT(@end))); | |
SET @start = @start - 1; | |
WITH [generator] (Id) AS | |
( | |
SELECT @start | |
UNION ALL | |
SELECT [Id] + 1 FROM generator WHERE [Id] < @sqr | |
) | |
, [combined] AS | |
( | |
SELECT TOP (@end) a.Id | |
FROM [generator] AS a | |
,[generator] AS b | |
,[generator] AS c | |
,[generator] AS d | |
,[generator] AS e | |
,[generator] AS f | |
,[generator] AS g | |
,[generator] AS h | |
) | |
INSERT INTO @table (Id) | |
SELECT @start + ROW_NUMBER() OVER (ORDER BY Id) | |
FROM [combined] | |
OPTION (MAXRECURSION 0) | |
RETURN; | |
END | |
GO | |
DECLARE @end BIGINT = 2000000; | |
PRINT FORMAT(@end, '0,0 ROWS REQUESTED') | |
SET STATISTICS TIME ON | |
SELECT FORMAT(COUNT(1), '0,0 ROWS RETURNED') FROM Range(1, @end); | |
SET STATISTICS TIME OFF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment