生成10000个连续的整数

时间:2014-02-06 09:30:31

标签: tsql sql-server-2005

有没有比这更好的方法来生成[0 ... 9999]:

SELECT
    (a3.id + a2.id + a1.id + a0.id) id
FROM
(   
    SELECT 0 id UNION ALL
    SELECT 1 UNION ALL
    SELECT 2 UNION ALL
    SELECT 3 UNION ALL
    SELECT 4 UNION ALL
    SELECT 5 UNION ALL
    SELECT 6 UNION ALL
    SELECT 7 UNION ALL
    SELECT 8 UNION ALL
    SELECT 9
) a0
CROSS JOIN
(
    SELECT 0 id UNION ALL
    SELECT 10 UNION ALL
    SELECT 20 UNION ALL
    SELECT 30 UNION ALL
    SELECT 40 UNION ALL
    SELECT 50 UNION ALL
    SELECT 60 UNION ALL
    SELECT 70 UNION ALL
    SELECT 80 UNION ALL
    SELECT 90
) a1
CROSS JOIN
(
    SELECT 0 id UNION ALL
    SELECT 100 UNION ALL
    SELECT 200 UNION ALL
    SELECT 300 UNION ALL
    SELECT 400 UNION ALL
    SELECT 500 UNION ALL
    SELECT 600 UNION ALL
    SELECT 700 UNION ALL
    SELECT 800 UNION ALL
    SELECT 900
) a2
CROSS JOIN
(
    SELECT 0 id UNION ALL
    SELECT 1000 UNION ALL
    SELECT 2000 UNION ALL
    SELECT 3000 UNION ALL
    SELECT 4000 UNION ALL
    SELECT 5000 UNION ALL
    SELECT 6000 UNION ALL
    SELECT 7000 UNION ALL
    SELECT 8000 UNION ALL
    SELECT 9000
) a3
ORDER BY id

任何反馈意见。

3 个答案:

答案 0 :(得分:2)

你可以这样写:

;WITH x as
(
  SELECT 0 id UNION ALL
  SELECT 1 UNION ALL
  SELECT 2 UNION ALL
  SELECT 3 UNION ALL
  SELECT 4 UNION ALL
  SELECT 5 UNION ALL
  SELECT 6 UNION ALL
  SELECT 7 UNION ALL
  SELECT 8 UNION ALL
  SELECT 9
)
SELECT
    row_number() over (order by (select 1))-1 id
FROM x a0
CROSS JOIN x a1
CROSS JOIN x a2
CROSS JOIN x a3

通过删除订单获得一点点。

答案 1 :(得分:0)

我不确定为什么从POST中删除了这个答案,这也产生了所需的输出

;WITH x as
(
    select id from 
    (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x(id)
)
SELECT
    (a3.id * 1000 + 
    a2.id * 100 + a1.id * 10 + a0.id) id
FROM x a2
CROSS JOIN x a0
CROSS JOIN x a1
CROSS JOIN x a3

答案 2 :(得分:0)

WITH a AS (
SELECT 0 AS a1
UNION ALL
SELECT a1+1 FROM a WHERE a1+1<10000
)
SELECT * FROM a
OPTION (Maxrecursion 10000)