根据SQL表中两列中的值生成数字列表

时间:2014-12-12 17:21:01

标签: sql sql-server

我们拥有的数据类型

From    To
1       5
6       10

现在,结果应该像 -

Series
1
2
3
4
5
6
7
8
9
10

我使用Cursor实现了这个结果,但只是想知道是否可以通过任何其他方法实现这一点。

2 个答案:

答案 0 :(得分:7)

你可以用两种方式做到这一点。

使用Recursive CTE生成表格中minimummaximum值之间的数字

CREATE TABLE #test([From] INT,[To]   INT)

INSERT #test
VALUES (1,5),(6,10) 

DECLARE @max INT

SELECT @max = Max([To])
FROM   #test;

WITH cte
     AS (SELECT Min([From]) Series
         FROM   #test
         UNION ALL
         SELECT Series + 1
         FROM   cte
         WHERE  Series < @max)
SELECT Series
FROM   cte a
       JOIN #test b
         ON a.Series BETWEEN b.[From] AND b.[To] 

或使用Master..spt_values获取数字

SELECT number As Series
FROM   master..spt_values a
       JOIN #test b
         ON a.number BETWEEN b.[From] AND b.[To]
WHERE  type = 'p' 

输出:

+------+
|Series|
+------+
|1     |
|2     |
|3     |
|4     |
|5     |
|6     |
|7     |
|8     |
|9     |
|10    |
+------+

答案 1 :(得分:1)

CREATE TABLE #tempnumber (num INT)
INSERT INTO #tempnumber
SELECT t.[to] FROM yourtable t
UNION
SELECT t1.[from] FROM yourtable t1


DECLARE @max INT, @min INT
SELECT @max = MAX(num) FROM #tempnumber
SELECT @min = MIN(num) FROM #tempnumber

;WITH Series(a) AS
(
 SELECT (SELECT @min)
 UNION ALL
 SELECT a+1 FROM Series WHERE a < (SELECT @max)
)
SELECT * FROM Series;