表x有 一列 ,程序每次生成id的时候都先从这里获取最大值再加1,初始值是A0001,然后到A9999的时候则是到B0001 共5位

drop table x
go
create table x(id varchar(10))
--insert into x values('A001')
go
with a as (
select ISNULL(max(id),'A0000') maxid from x)
insert into x (id)
select
case when RIGHT(maxid,4)<9999
THEN LEFT(maxid,1)+RIGHT('000'+CAST(RIGHT(maxid,4)+1 AS VARCHAR(10)),4)
ELSE CHAR(ASCII(LEFT(maxid,1))+1)+'0001'
end
from a
go 10000
select * from x
go

  

--两位

drop table 
go
create table x(id varchar(10))
go
with as (
select ISNULL(max(id),'A00') maxid from x)
insert into x (id)
select 
 case when substring(maxid,2,30) = '99' then CHAR(ascii(left(maxid,1)) +1) + '01'
      else LEFT(maxid,1) + right('0000' cast((SUBSTRING(maxid,2,30) + 1 ) as varchar(30)) ,2)
 end     
 from 
 go 200
select from 
go
原文地址:https://www.cnblogs.com/yangpeng-jingjing/p/5063827.html