sql用函数解决编码由字母和数字结合起来自动增长的问题
sql用函数解决编码由字母和数字结合起来自动增长的问题
方法一:
--实现aaaa_00001-aaaa_99999
1 create function 编码() 2 returns varchar(9) 3 begin 4 declare @编号 varchar(9) 5 declare @id int 6 select top 1 @编号=编号 from b order by 编号 desc 7 if @@rowcount=0 8 set @编号='aaaa_0000' 9 else 10 begin 11 set @id=cast(substring(@编号,6,9) as int) +1 12 set @编号='aaaa_'+replicate(0,4 - len(@id))+cast(@id as varchar(4)) 13 end return @编号 14 end www.2cto.com 15 go 16 --创建表 17 create table b 18 (编号 varchar(10) default dbo.编码(b.编号), 19 name1 varchar(10) 20 ) 21 go 22 --插入表 23 insert into b values(default,'aa') 24 insert into b values(default,'bb') 25 --查询 26 select * from b 27 28 方法二: 29 --实现编码bh000001的自动增长 30 create 31 function f_nextbh() 32 returns 33 char(8) 34 as 35 begin 36 return 37 (select 'bh'+right(1000001+isnull(right(max(bh),6),0),6)+1 38 from tb with(xlock,paglock)) 39 end 40 go 41 --创建表 42 create table tb 43 (bh char(8) default dbo.f_nextbh(), 44 col int) www.2cto.com 45 --插入表的数据 46 begin tran --开始事务 47 insert into tb(col) values(1) 48 insert into tb(col) values(2) 49 insert into tb(col) values(3) 50 delete tb where col=3 51 insert into tb(col) values(4) 52 insert into tb(bh,col) values(dbo.f_nextbh(),14) 53 commit tran --提交事务 54 --查询表 55 select * from tb 56 drop table tb 57 drop function f_nextbh