您的位置:首页 > 其它

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

2009-12-17 07:26 387 查看
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

上面的存储过程在触发器中调用即可.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: