select 'GMN'+right(1000000+a.id+1,6) from
(select cast(right(id,len(id)-len('GMN')) as int) as id from t_test where left(id,3)='GMN') as a
left join
(select min(cast(right(id,len(id)-len('GMN')) as int)) as id from t_test where left(id,3)='GMN'
union all
select max(cast(right(id,len(id)-len('GMN')) as int)) from t_test where left(id,3)='GMN') as b
on a.id=b.id
where b.id is null and not exists (select * from t_test where left(id,3)='GMN' and right(id,len(id)-len('GMN'))=a.id+1)
create table tb(id varchar(20))
Insert into tb
select 'GMN000001'
union all select 'GMN000002'
union all select 'GMN000003'
union all select 'GMN000004'
union all select 'GMN000005'
union all select 'GMN000006'
union all select 'GMN000008'
union all select 'ABS000008'
select * from
(select ID=left(id,3)+replicate('0',6-len(cast(right(id,6) as numeric)+1))+cast(cast(right(id,6) as numeric)+1 as varchar) from tb where left(id,3)='GMN')a
where not exists(select id from tb where id=a.id) and id<=(select max(id) from tb where left(id,3)='GMN')
--构建一个临时表,存储自动编号
declare @max int
declare @min int
select max(substring(id,3,len(id)-1)) into @max,min(substring(id,3,len(id)-1)) into @min
from table1
declare @temp table(id varchar(20) )
while @max>=@min
begin
insert into @temp values('GMN'+left('000000'+convert(varchar(6),@max),6))
set @max =@max-1
end
--获得被删除的ID
select id
from @temp
where id not in(select id from table1)