根据一定规则为数据表新增记录自动编号的存储过程

 

CREATE PROCEDURE  dbo.AutoGenCustomerSN
 AS
--自动生成单据客户编号

 declare @客户ID int,@类别编号 varchar(30),@客户编号 varchar(30),@客户名称 varchar(50),@客户简称 varchar(30),@所属市县 varchar(50)

 declare @WFNum integer, @BH varchar(20),@count int

 --先清除所属市县与编号不匹配的客户的编号
 update 客户资料表 set 客户编号='' where substring(所属市县,1,6)<> substring(客户编号,1,6)

 declare Master_cursor cursor  for
        SELECT distinct 所属市县 from 客户资料表 order by 所属市县
 
   open Master_cursor
   fetch next from Master_cursor into @所属市县
   while (@@fetch_status = 0)
   begin
  --select @count=convert(int ,substring(max(客户编号) ,7,3) )  from 客户资料表 where 所属市县=@所属市县 and  isnull(客户编号,'')<>''
                         -- select @count=count(*) from 客户资料表 where 所属市县=@所属市县 and  isnull(客户编号,'')<>''
  --下述算法正常工作的前提是, 客户编号必须是6位编号加3位流水号, 而且6位编号必须是所属市县的前六位, 切记, 切记
  select @count=convert(int ,substring(max(客户编号) ,7,3) )  from 客户资料表 where 所属市县=@所属市县 and  客户编号 like substring(@所属市县,1,6)+'%'
  select @WFNum=isnull(@count,0)+100001
  declare detail_cursor cursor  for
         SELECT 客户ID,类别编号,客户编号,客户名称,客户简称
   from 客户资料表 where  isnull(客户编号,'')='' and 所属市县=@所属市县 order by 客户名称 
    open detail_cursor
    fetch next from detail_cursor into @客户ID,@类别编号,@客户编号,@客户名称,@客户简称
    while (@@fetch_status = 0)
    begin

   select @BH=substring(@所属市县,1,6)+Substring(Convert(varchar(6),@WFNum),4,3)
   update 客户资料表 set 客户编号=@BH where 客户ID=@客户ID
   select @WFNum=@WFNum+1

   fetch next from detail_cursor into @客户ID,@类别编号,@客户编号,@客户名称,@客户简称
    end
    close detail_cursor
    deallocate detail_cursor
 
  fetch next from Master_cursor into @所属市县
   end
   close Master_cursor
   deallocate Master_cursor
GO

 

上面的存储过程在触发器中调用即可.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值