2009-02-13 12 views
7

Diciamo che ho la seguente tabella in MS SQL 2000Come dividere Sql Int Valore in più righe

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

ho bisogno di visualizzare più righe in base alla quantità, quindi ho bisogno il seguente output:

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

Qualche idea su come realizzare questo?

risposta

3

Questo funziona bene, non c'è bisogno di cursori su questo. Potrebbe anche essere possibile estrarre qualcosa senza una tabella numerica.

Nota Se si sta cercando questo tipo di soluzione, manterrei una tabella numerica e non la ricreerò ogni volta che ho eseguito la 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 
+0

ammesso che se @i fosse impostato su max di quantità da #splitme, sarebbe stato perfetto. Ad ogni modo +1! – Learning

+0

seleziona @i = max (quantità) da #splitme .... –

+0

btw .. Chi ha downvoted questo, puoi spiegare perché? –

0
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 

Tra l'altro, i cursori sono generalmente considerato il male. Quindi raccomanderò entrambi contro qualcosa di simile, e ringrazio tutti in anticipo per le loro fiamme;) (Ma dovrebbe funzionare)

Problemi correlati