这是一个简单的方法,您只需更改@nextGroup 变量。它使用ROW_NUMBER()。
declare @table table ([Group] int, Line int, Brand char(2), [Param] varchar(64), Value varchar(256))
insert into @table values
(8005,1,'MO','CUT SPEED','55 Series'),
(8005,2,'MO','CUT BLADE','450 Series'),
(8005,3,'MO','CUT SPEED OV','60 Series'),
(8005,4,'MO','CUT BLADE OV','475 Series'),
(8005,5,'MO','CUT COMMENTS','Slow'),
(8005,6,'MO','CUT OV COMMENTS','Fast')
declare @nextGroup int = 8010
declare @currentGroup int = (select max([Group]) from @table where [Group] < @nextGroup)
declare @nextLine int = (select max([Line]) from @table where [Group] = @currentGroup)
insert into @table
select
@nextGroup as [Group]
,@nextline + row_number() over (order by (select null)) as Line
,t.Brand
,t.Param
,t.Value
from @table t
where t.[Group] = @currentGroup
set @nextGroup = 8015
set @currentGroup = (select max([Group]) from @table where [Group] < @nextGroup)
set @nextLine = (select max([Line]) from @table where [Group] = @currentGroup)
insert into @table
select
@nextGroup as [Group]
,@nextline + row_number() over (order by (select null)) as Line
,t.Brand
,t.Param
,t.Value
from @table t
where t.[Group] = @currentGroup
select * from @table
使用光标
--test data
declare @table table ([Group] int, Line int, Brand char(2), [Param] varchar(64), Value varchar(256))
insert into @table values
(8005,1,'MO','CUT SPEED','55 Series'),
(8005,2,'MO','CUT BLADE','450 Series'),
(8005,3,'MO','CUT SPEED OV','60 Series'),
(8005,4,'MO','CUT BLADE OV','475 Series'),
(8005,5,'MO','CUT COMMENTS','Slow'),
(8005,6,'MO','CUT OV COMMENTS','Fast')
--variables for handling data conditions
declare @nextGroup int
declare @currentGroup int
declare @nextLine int
--table with all the group numbers to use
declare @groupTable table (nextGroup int)
insert into @groupTable values
(8010),
(8015),
(8020)
--cursor to loop through the set based inserts
declare groupCursor cursor fast_forward for
select nextGroup from @groupTable
open groupCursor
fetch next from groupCursor into @nextGroup
while @@FETCH_STATUS = 0
begin
--get the last group inserted. The where condition isn't really needed
set @currentGroup = (select max([Group]) from @table where [Group] < @nextGroup)
--this figures out what the last line number was in the table
set @nextLine = (select max([Line]) from @table where [Group] = @currentGroup)
insert into @table
select
@nextGroup as [Group]
--Here we increase the line number by 1 according to the last one
,@nextLine + row_number() over (order by (select null)) as Line
,t.Brand
,t.Param
,t.Value
from @table t
where t.[Group] = @currentGroup
fetch next from groupCursor into @nextGroup
end
close groupCursor
deallocate groupCursor
select * from @table