客户需要将表中统计好的数据还原成统计前的原始记录

例如:

ID Name QTYCount
100 Name1 1
101 Name2 2
102 Name3 3
103 Name4 4
104 Name5 5

还原为:

ID Name QTY
100 Name1 1
101 Name2 1
102 Name2 1
103 Name3 1
104 Name3 1
105 Name3 1
106 Name4 1
107 Name4 1
108 Name4 1
109 Name4 1
110 Name5 1
111 Name5 1
112 Name5 1
113 Name5 1
114 Name5 1

原始数据已经找不到,只能通过现有数据反推

--统计结果表
CREATE TABLE [dbo].[CopyTest](
[ID] [int] IDENTITY(100,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[QTY] [float] NULL
) ON [PRIMARY] --将统计结果还原为原始记录表
CREATE TABLE [dbo].[CopyTestResult](
[ID] [int] IDENTITY(100,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[QTY] [float] NULL
) ON [PRIMARY] --生成测试数据
Declare @n bigint
Declare @Sql nvarchar(225)
set @n=1
while @n<6
begin
Set @Sql='Insert into CopyTest Values(''Name'+ convert(varchar(5),@n) +''','+convert(varchar(5),@n)+')'
Exec (@Sql)
set @n=@n+1
End

 由于数据量比较大,而且只是临时的需求,想想游标最合适。

Declare CopyRowByNumber Cursor  For Select * from CopyTest
Open CopyRowByNumber declare @id int
declare @name nvarchar(50)
declare @qty float
declare @allCount int
set @allCount=0
Fetch Next From CopyRowByNumber into @id,@name,@qty
while @@FETCH_STATUS=0
Begin
--根据Qty循环生成数据
while @qty>=1
begin
set @allCount=@allCount+1
insert into CopyTestResult Values(@name,1)
set @qty=@qty-1
end Fetch Next From CopyRowByNumber into @id,@name,@qty End
Close CopyRowByNumber
DEALLOCATE CopyRowByNumber

ok。

04-27 21:13