Skip to content

Instantly share code, notes, and snippets.

@BrentOzar
Created July 25, 2024 09:44
Show Gist options
  • Save BrentOzar/9e8834098ec320ba8754399d21a612bc to your computer and use it in GitHub Desktop.
Save BrentOzar/9e8834098ec320ba8754399d21a612bc to your computer and use it in GitHub Desktop.
Dynamically generating large queries
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