--方法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

解决方案 »

  1.   

    --方法2,如果code允许插入空值,则插入后再更新insert 表B(name) select * from 表A
    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
      

  2.   

    --考虑到输入条件的问题,对上述方法改进
    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
    ')
      

  3.   


    --方法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
      

  4.   


    --方法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