tags:

views:

71

answers:

4

Is there a better way to generate a range of numbers in SQL than below? I'm using MySql.

SELECT tens.x + ones.x + 1
FROM
(SELECT 0 x UNION ALL
 SELECT 1 x UNION ALL
 SELECT 2 x UNION ALL
 ...
 SELECT 9 x ) ones

CROSS JOIN

(SELECT 0 x UNION ALL
 SELECT 10 x UNION ALL
 SELECT 20 x UNION ALL
 ...
 SELECT 90 x ) tens;
+1  A: 

Using Sql server 2005+ you can make use of CTEs

DECLARE @Start INT, @End INT

SELECT  @Start = 0, @End = 100000

;WITH Numbers AS (
     SELECT @Start Num
     UNION ALL
     SELECT Num + 1
     FROM Numbers
     WHERE Num < @End
)
SELECT  *
FROM    Numbers
OPTION (MAXRECURSION 0);
astander
Just be aware that the default maximum number of recursions is 100. This can be changed to maximum of 32767 by calling: option (maxrecursion 32767). see http://msdn.microsoft.com/en-us/library/ms175972.aspx
kristof
Try that query, it goes past 32767 as specified by @End = 100000
astander
true, my bad somehow I didn't notice that when OPTION (MAXRECURSION 0) is specified there is no limit on the recursions. Thanks
kristof
Its all good X-)
astander
+1  A: 

A common way to do that in Oracle is to abuse the rownum pseudocolumn:

select rownum from all_objects where rownum<=100;
ammoQ
+1  A: 

PostgreSQL allows you to use:

select * from generate_series(2,4);
 generate_series
-----------------
               2
               3
               4

That is specific for the PostgresSQL engine. But it shouldn't be to hard to write a stored proedure for your data base.

Frank Bollack
A: 

Why not loop? like

BEGIN
      DECLARE a INT Default 0 ;
      simple_loop: LOOP
         SET a=a+1;
         insert into mytable(id) values(a);
         IF a=1000 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;

Modified from Mysql For Loop

Pardon me if the syntax is wrong as I am a pure SQL SERVER guy(:

priyanka.sarkar