Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 Script Library
 Numbers table from cross join
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Andrew Zwicker
Starting Member

11 Posts

Posted - 05/29/2011 :  00:36:00  Show Profile  Reply with Quote
I recently profiled on my site at a query that can be used for using cross joins to populate a numbers table. I'm reposting the sql for doing this here. This runs in ~3 seconds and currently inserts 800,000 records. This can be modified to insert fewer or more numbers as needed.

A few examples of number tables in use can be found here [scroll halfway down]:

Here's the SQL. I used a table variable @numbers for the numbers 0-9, but if you're using SQL Server 2000, you'll need to instead use a temp table [#numbers].

create table numbers(number int)

----- Use a table variable 
      num INT
----- Populate a table with numbers 0 to 9
DECLARE @counter INT
SET @counter = 0
While @counter < 10
      INSERT INTO @numbers VALUES(@counter)
      SET @counter = @counter + 1
INSERT INTO numbers (number)
      n100000place.num*100000 +
      n10000place.num*10000 +
      n1000place.num*1000 +
      n100place.num*100 + 
      n10place.num*10 + 
) AS 'number'
FROM @numbers n1place 
CROSS JOIN @numbers n10place
CROSS JOIN @numbers n100place
CROSS JOIN @numbers n1000place
CROSS JOIN @numbers n10000place
CROSS JOIN @numbers n100000place
WHERE n100000place.num < 8 -----  < 800000
ORDER BY number

  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2019 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.02 seconds. Powered By: Snitz Forums 2000