2014-02-06 47 views
2

是否有更好的方法來生成[0 ... 9999]比這產生連續10000個整數

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

http://www.sqlperformance.com/2013/01/t-sql-queries/生成一個集1 –

+0

可能重複的[SQL,輔助數字表](http://stackoverflow.com/questions/10819/sql-auxiliary-table-of-numbers) –

+0

我不認爲這是真的。我問一個非常具體的問題,而另一個是非常通用的... – cs0815

回答

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 

通過你所獲得的一點點拆卸順序。

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 
+0

我刪除了我的文章,因爲它不適用於sql-server 2005.重寫它 –

+0

是的,這是正確的,它適用於2008年及以上 –

+0

獲取語法錯誤那一個... – cs0815

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) 
+0

如果你看@ TimSchmelter的鏈接。你會發現這樣的表現並不好(14毫秒比1毫秒) –