Generate recursive N integers in SQL
MS SQL Server
I want to generate a table with 1,000,000 sequential ids because I am wasteful and scourge upon humanity
Step 1 - Create temp table
Step 2 - Use recursive Common Table Expression with UNION ALL
Generate the range with the SELECT n+1 FROM t WHERE n < 1000000
Step 3 - Insert the generated ids into the table
Be careful as SQL server will try to protect you from this profoundly bad way to generate ids with a max recursion limit of 100, but you can override that to infinity with the MAXRECURSION o
option
MAXRECURSION number
Specifies the maximum number of recursions allowed for this query. number is a nonnegative integer between 0 and 32,767. When 0 is specified, no limit is applied. If this option isn't specified, the default limit for the server is 100.
DROP TABLE IF EXISTS #myvalues
CREATE TABLE #myvalues(id INT primary key);
WITH t(n) AS (
SELECT 0
UNION ALL
SELECT n+1 FROM t WHERE n < 1000000
)
INSERT INTO #myvalues
SELECT n
FROM t
OPTION (MAXRECURSION 0);
SELECT *
FROM #myvalues
ORDER BY Id