insert multiple records into table based on values in colume

后端 未结 2 1496
面向向阳花
面向向阳花 2021-01-24 16:39

I have a table basetable as given below

id name qty price
2  a    2    20
3  d    3    10
4  b    5    60

i want to insert the rec

2条回答
  •  长发绾君心
    2021-01-24 17:38

    You can use a recursive CTE to generate the data:

    with cte as (
          select bt.id, bt.name, bt.qty, bt.price, 1 as cnt
          from basetable bt
          union all
          select bt.id, bt.name, bt.qty, bt.price, cnt + 1
          from cte
          where cnt < bt.qty
         )
    select id, name, 1 as qty, price
    from cte;
    

    If you want to put the data in another table, then either use an insert before the select or an into after the select.

    Note: If your quantities get really big, you might have to investigate the MAXRECURSION option.

提交回复
热议问题