Created
July 25, 2024 09:44
-
-
Save BrentOzar/9e8834098ec320ba8754399d21a612bc to your computer and use it in GitHub Desktop.
Dynamically generating large queries
This file contains 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
DECLARE @NumberOfLayers INT = 1000; | |
SELECT 0 AS Ordered, 'DECLARE @t TABLE (Id INT PRIMARY KEY CLUSTERED);' | |
UNION | |
SELECT 1 AS Ordered, 'WITH CTE1 AS (SELECT * FROM @t t1)' | |
UNION | |
SELECT value AS Ordered, ', CTE' + CAST(value AS VARCHAR(10)) + ' AS (SELECT cA.* ' + | |
' FROM CTE' + CAST(value - 1 AS VARCHAR(10)) + ' cA INNER JOIN ' + | |
' CTE' + CAST(value - 1 AS VARCHAR(10)) + ' cB ON cA.Id = cB.Id) ' | |
FROM GENERATE_SERIES(2,@NumberOfLayers) | |
UNION | |
SELECT @NumberOfLayers + 1 AS Ordered, 'SELECT * FROM CTE' + CAST(@NumberOfLayers AS VARCHAR(10)) | |
ORDER BY 1 | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment