3

I have a table like this

Name         Qty   
-----        -----
BD             2
SD             1
XE             3

I need to return this table records repeated according to the field Qty value. for example first row would be repeated twice with all same values.

I was thinking to use nested FOR Select inside stored procedure with return parameters

For Select name, qty from mytable into :name, :qty do
  begin
    if (qty > 1 ) then begin
      i = 1; -- should I start from 2 ?
      while (i <= :qty) do
      begin

        for select name, qty from mytable into :name1, :qty1 do ...

        SUSPEND;

        i = i + 1;
      end


    end

    SUSPEND;
end

Can this stored procedure return the correct result or should I use another way ?

I use FireBird 2.5 and please discard any typos in the previous SQL I am looking only to main idea.

4

2 回答 2

3

如果您有一个数字表,这很简单:

SELECT
    OT.Name
FROM
    OrigTable AS OT
    INNER JOIN Numbers AS N ON N.Number BETWEEN 1 AND OT.Qty

我不熟悉 Firebird,但我相信这种非常简单的语法适用。

于 2013-10-18T18:44:23.640 回答
3

您可以使用从 2.1 版开始支持的递归 CTE来执行此操作,例如

WITH RECURSIVE tQty AS(
    SELECT ta.name, ta.qty
       FROM T ta
       WHERE(ta.qty > 0)
 UNION ALL
    SELECT tb.name, tb.qty-1
       FROM tQty tb
       WHERE(tb.qty-1 > 0)
 )
 SELECT name,qty FROM tQty
       ORDER BY name
于 2013-10-19T09:25:01.167 回答