根据变量列多次插入唯一值

问题描述 投票:0回答:3

我的表中有以下几列:

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
sql sql-server tsql sql-insert
3个回答
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)


1
投票

我更喜欢这样的事。一旦开始使用较大的行集,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;

0
投票

一个选项使用递归公用表表达式从源表生成行,然后可以将其插入目标表:

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
© www.soinside.com 2019 - 2024. All rights reserved.