Generating Rows Based on Column Value

前端 未结 3 444
情书的邮戳
情书的邮戳 2020-12-19 17:15

One of my tables in my database contains rows with requisition numbers and other related info. I am trying to create a second table (populated with an INSERT INTO

相关标签:
3条回答
  • 2020-12-19 17:25

    You need recursive way :

    with t as (
         select Requisition, 1 as start, Quantity
         from table
         union all
         select Requisition, start + 1, Quantity
         from t
         where start < Quantity
     ) 
    select Requisition, Quantity, start as Series  
    from t; 
    

    However, by default it has limited to only 100 Quantities, if you have a more then you need to specify the query hint by using option (maxrecursion 0).

    0 讨论(0)
  • 2020-12-19 17:34

    A simple method uses recursive CTEs:

    with cte as (
          select requsition, quantity, 1 as series
          from t
          union all
          select requsition, quantity, 1 + series
          from t
          where lev < quantity
        )
    select requsition, quantity, series
    from cte;
    

    With default setting, this works up to a quantity of 100. For larger quantities, you can add option (maxrecursion 0) to the query.

    0 讨论(0)
  • 2020-12-19 17:38

    Non-recursive way:

    SELECT *
    FROM tab t
    CROSS APPLY (SELECT n
                 FROM (SELECT ROW_NUMBER() OVER(ORDER BY 1/0) AS n
                       FROM master..spt_values s1) AS sub
                 WHERE  sub.n <= t.Quantity) AS s2(Series);
    

    db<>fiddle demo

    0 讨论(0)
提交回复
热议问题