--方法1,用临时表select id=identity(int,1,1),name into #t from 表A
insert 表B(name,code)
select name,'M'+right('000000'+cast(id as varchar),6) from #t
drop table #t
insert 表B(name,code)
select name,'M'+right('000000'+cast(id as varchar),6) from #t
drop table #t
declare @i int
set @i=0
update 表B set @i=@i+1,code='M'+right('000000'+cast(@i as varchar),6)
where code is null
declare @tj char(7)
set @tj='M000001' --输入条件
--临时表的处理方法
declare @h varchar(10),@i varchar(10),@fmt varchar(10),@bhlen varchar(10)
select @bhlen=patindex('%[0-9]%',@tj)
,@h=left(@tj,@bhlen-1)
,@bhlen=len(@tj)-@bhlen+1
,@i=right(@tj,@bhlen)
,@fmt=replicate('0',@bhlen)
exec('
select id=identity(int,'+@i+',1),name into #t from 表A
insert 表B(name,code)
select name,'''+@h+'''+right('''+@fmt+'''+cast(id as varchar),'+@bhlen+') from #t
')
--方法2的改进
declare @tj char(7)
set @tj='M000001' --输入条件
--处理方法
declare @h varchar(10),@i int,@fmt varchar(10),@bhlen int
select @bhlen=patindex('%[0-9]%',@tj)
,@h=left(@tj,@bhlen-1)
,@bhlen=len(@tj)-@bhlen+1
,@i=right(@tj,@bhlen)-1
,@fmt=replicate('0',@bhlen)insert 表B(name) select * from 表A
update 表B set @i=@i+1,code=@h+right(@fmt+cast(@i as varchar),@bhlen)
where code is null
--方法2的改进
declare @tj char(7)
set @tj='M000001' --输入条件
--处理方法
declare @h varchar(10),@i int,@fmt varchar(10),@bhlen int
select @bhlen=patindex('%[0-9]%',@tj)
,@h=left(@tj,@bhlen-1)
,@bhlen=len(@tj)-@bhlen+1
,@i=right(@tj,@bhlen)-1
,@fmt=replicate('0',@bhlen)insert 表B(name) select * from 表A
update 表B set @i=@i+1,code=@h+right(@fmt+cast(@i as varchar),@bhlen)
where code is null