我的表中有以下几列:
PromotionID | NumberOfCodes
1 10
2 5
我需要多次将PromotionID
插入新的SQL表中-取决于NumberOfCodes
中的值。
因此,鉴于以上所述,我的结果集应显示为:
PromotionID
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
您需要递归cte:
with r_cte as (
select t.PromotionID, 1 as start, NumberOfCodes
from table t
union all
select id, start + 1, NumberOfCodes
from r_cte
where start < NumberOfCodes
)
insert into table (PromotionID)
select PromotionID
from r_cte
order by PromotionID;
默认递归级别100,如果还有NumberOfCodes,请使用查询提示option(maxrecursion 0)
。
我更喜欢这样的事。一旦开始使用较大的行集,rCTe的性能就会很快下降:
WITH N AS(
SELECT N
FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
FROM N N1, N N2) --Up to 100 rows. Add more cross joins to N for more rows
SELECT YT.PromotionID
FROM dbo.YourTable YT
JOIN Tally T ON YT.NumberOfCodes >= T.I;
一个选项使用递归公用表表达式从源表生成行,然后可以将其插入目标表:
with cte as (
select promotion_id, number_of_codes n from sourcetable
union all select promotion_id, n - 1 from mytable where n > 1
)
insert into targettable (promotion_id)
select promotion_id from cte