views:

31

answers:

2

Hi there

I have 3 column (ID, Start and End) in TSQL.

ID; Start; END
1; 1; 5;
2; 10; 15;

So it will generate number like:

1, 1
1, 2
1, 3
1, 4
1, 5
2, 10
2, 11
2, 12
2, 13
2, 14
2, 15

Again all I can think of is cursor but is there any better way?

+4  A: 

Something like this (untested)

;WITH cNumbers AS
(
   SELECT
       ROW_NUMBER() OVER (ORDER BY c1.object_id) AS ArbitraryNumber
   FROM
       sys.columns c1 CROSS JOIN sys.columns c2
)
SELECT
    M.ID, N.ArbritraryNumber
FROM
    MyTable M
    JOIN
    cNumbers N ON N.ArbitraryNumber BETWEEN M.Start AND M.End

Edit:

The cross join gives 298,116 rows in my tempdb. And 1,865,956 in a user DB. If nearly 300k isn't enough, add another CROSS JOIN.

This gives me 162,771,336 in tempdb and 2,548,895,896 in a user DB:

SELECT
    COUNT_BIG(*) --note bigint
FROM
    sys.columns c1 CROSS JOIN sys.columns c2 CROSS JOIN sys.columns c3
gbn
How are we sure that Arbitrary Number will cover all the range which might be required?
Nitin Midha
Ah the CTE stuff ... I didn't though about that. I will explore this
dewacorp.alliances
@Nitin Midha: see my edit please
gbn
@gbn: the number that I got is phone number range which is 0296620382 - 096620399. So the number it never get 10 digits. So is it necessary to go through this c1.ObjectID stuff ?
dewacorp.alliances
@dewacorp.alliances: If I understand correctly, add another CROSS JOIN to give more numbers. c1.ObjectID is random. I use sys.columns because it always has at least 500 rows or so
gbn
@gbn: I did try that and it takes while in the query to generate a range between 0296620382 - 096620399. Is there any other approach?
dewacorp.alliances
+2  A: 

A CTE approach is easy

with tab as(
select 1 as id, 1 as start, 5 as en
union all
select 2, 10, 15),
 cte as(
select id,start,en from tab
union all
select id,start+1 , en from cte where start+1<=en)
select id,start from cte
order by id
josephj1989
@josephj1989: Thanks for this. I like this approach cause it doesn't require me to create sequential number which is good. It's fast as well.
dewacorp.alliances
@josepj1989: I got an issue which basically the recursive more than 100 numbers. I can solve this by appending OPTION (MACRECURSION 1000) but not sure where to put this.
dewacorp.alliances