A simple way uses recursive CTEs:
with cte as (
select col1, col2, factor, 1 as lev
from t
union all
select col1, col2, factor - 1, lev + 1
from cte
where factor > 1
)
select col1, col2, 1 as factor -- or perhaps lev if you want an incrementing value
from cte;
Two notes:
- You can use this for an
insert
or select into
.
- If
factor
can be more than 100, then add option (maxrecursion 0)
to the query.
Recursive CTEs have surprisingly decent performance. But if you need to generate zillions of rows, then some sort of number/tally table would be useful. For instance, if your base table had enough rows:
select col1, col2, 1 as factor
from t join
(select row_number() over (order by (select null)) as n
from t
) n
on n.n <= t.factor