Creating SQL server table with sequential numbers using CROSS JOIN
Posted by Max | Posted in programming | Posted on 03-09-2009
0
Use the following SQL script to create a table with sequentional numbers. This example inserts 10000 records and performs faster than a similar query using “while” loop.
The original code was taken from here
-- Be sure to drop the numbers table if it exists IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Numbers') DROP TABLE Numbers GO -- Now re-create it and fill it with sequential numbers starting at 1 SELECT TOP 10000 IDENTITY(INT,1,1) AS Num INTO dbo.Numbers FROM master.INFORMATION_SCHEMA.COLUMNS i1 CROSS JOIN master.INFORMATION_SCHEMA.COLUMNS i2 CROSS JOIN master.INFORMATION_SCHEMA.COLUMNS i3; GO -- Add a primary key/clustered index to the numbers table ALTER TABLE dbo.Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Num); GO

