我正在使用SQL Server 2008.我有一个表temp
:
select * from temp
返回:
name start_limit end_limit
-------------------------------
j 2 7
t 1 9
现在我想要生成以下序列
name allowed values
----------------------
j 2
j 3
j 4
j 5
j 6
j 7
t 1
t 2
t 3
t 4
t 5
t 6
t 7
t 8
t 9
我该怎么办?
答案 0 :(得分:3)
这将完美地运作:
;with a as(
select name,start_limit as [allowed values] from temp
union all
select b.name,a.[allowed values]+1 as [allowed values] from temp b inner join a on b.name=a.name and b.end_limit>a.[allowed values]
)
select * from a order by name,seq;
答案 1 :(得分:3)
以下是使用计数表的一种方法,不需要递归
;WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4)
SELECT a.name,c.N
FROM ctetally c
JOIN Yourtable a
ON c.N BETWEEN a.start_limit AND a.end_limit