多次复制一行

时间:2012-03-16 11:11:58

标签: sql sql-server tsql

基本上我想复制一行可变的次数。 我有一个具有以下结构的表:

CREATE TABLE [dbo].[Start](
[ID] [int] NOT NULL,
[Apt] [int] NOT NULL,
[Cost] [int] NOT NULL)

我想复制此表中的每一行(Apt-1)次,所以最后会有#Apt行。此外,对于每个新行,Cost的值递减,直到达到0.ID将与没有主键的ID相同。如果我有这样的记录:

1    5    3

我需要在同一个表中插入4个新行,它们应该如下所示

1    5    2
1    5    1
1    5    0
1    5    0

到目前为止,我已尝试了很多方法,但我无法使其发挥作用。非常感谢!

2 个答案:

答案 0 :(得分:0)

尝试:

;with cte as 
(select [ID], [Apt], [Cost], 1 counter from [Start]
 union all
 select [ID], 
        [Apt], 
        case sign([Cost]) when 1 then [Cost]-1 else 0 end [Cost], 
        counter+1 counter 
 from cte where counter < [Apt])
select [ID], [Apt], [Cost]
from cte

答案 1 :(得分:0)

试试这个

DECLARE  @Start TABLE ( 
[ID] [int] NOT NULL, 
[Apt] [int] NOT NULL, 
[Cost] [int] NOT NULL) 

INSERT @Start (ID, Apt, Cost)
VALUES  (1, 5, 3)



; WITH CTE_DIGS AS (
    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS rn
    FROM master.sys.all_columns AS a
)
INSERT @Start (ID, Apt, Cost)
SELECT ID, Apt, CASE WHEN Cost - rn < 0 THEN 0 ELSE Cost - rn END
FROM @Start
INNER JOIN CTE_DIGS
    ON Apt > rn