tags:

views:

1231

answers:

3

Lets say I have the following table in MS SQL 2000

Id | description | quantity |
-------------------------------
1    my desc          3
2    desc 2           2

I need to display multiple rows based on the quantity, so I need the following output:

Id | description | quantity |
-----------------------------
1    my desc          1
1    my desc          1
1    my desc          1
2    desc 2           1
2    desc 2           1

Any ideas how to accomplish this?

A: 
DECLARE @Id INT
DECLARE @Description VARCHAR(32)
DECLARE @Quantity INT
DECLARE @Results TABLE (Id INT, [description] VARCHAR(32), quantity INT)
DECLARE MyCursor CURSOR FOR
    SELECT Id, [description], quantity
    FROM
        MyTable

OPEN MyCursor

FETCH NEXT FROM MyCursor INTO @Id, @Description, @Quantity

WHILE @@FETCH_STATUS = 0
BEGIN
    WHILE @Quantity > 0
    BEGIN
        INSERT INTO @Results (
            Id,
            [description],
            quantity
        ) VALUES (
            @Id,
            @Description,
            1
        )
        SET @Quantity = @Quantity - 1
    END
    FETCH NEXT FROM MyCursor INTO @Id, @Description, @Quantity
END

CLOSE MyCursor
DEALLOCATE MyCursor

SELECT *
FROM
    @Results

By the way, cursors are generally considered evil. So I will both recommend against something like this, and thank everyone in advance for their flames ;) (But it should work)

Sean Bright
A: 

Interesting question, and I don't have a good answer (outside of using a cursor and while loop as Sean suggested).

I'm just curious, what do you do if the quantity is negative? Delete a result row/rows from the set of the previous id? :)

jwolly2
in my case the quantity would never be negative because its the quantity of an order item.
Josh Pollard
+1  A: 

This works just fine, no need for any cursors on this one. It may be possible to fangle something out without a number table as well.

Note if going for this kind of solution I would keep a number table around and not recreate it every time I ran the query.

create table #splitme (Id int, description varchar(255), quantity int) 
insert #splitme values (1    ,'my desc',          3)
insert #splitme values (2    ,'desc 2',           2)

create table #numbers (num int identity primary key) 
declare @i int 
select @i = max(quantity) from #splitme
while @i > 0
begin   
    insert #numbers default values 
    set @i = @i - 1 
end

select Id, description, 1 from #splitme 
join #numbers on num <= quantity
Sam Saffron
admittedly , if @i was set to max of quantity from #splitme , it would have been perfect. Anyway +1 !
Learning
select @i = max(quantity) from #splitme ....
Sam Saffron
btw .. whoever downvoted this can you explain why?
Sam Saffron
I meant in the while loop so that you do not loop for 10000 times (what if one of the Quantity was 10001) . Selecting max would eliminate that case.
Learning
See the updated query
Sam Saffron