方法一:
--实现aaaa_00001-aaaa_99999
create function 编码()
returns varchar(9)
begin
declare @编号 varchar(9)
declare @id int
select top 1 @编号=编号 from b order by 编号 desc
if @@rowcount=0
set @编号='aaaa_0000'
else
begin
set @id=cast(substring(@编号,6,9) as int) +1
set @编号='aaaa_'+replicate(0,4 - len(@id))+cast(@id as varchar(4))
end return @编号
end
go
--创建表
create table b
(编号 varchar(10) default dbo.编码(b.编号),
name1 varchar(10)
)
go
--插入表
insert into b values(default,'aa')
insert into b values(default,'bb')
--查询
select * from b
方法二:
--实现编码bh000001的自动增长
create
function f_nextbh()
returns
char(8)
as
begin
return
(select 'bh'+right(1000001+isnull(right(max(bh),6),0),6)+1
from tb with(xlock,paglock))
end
go
--创建表
create table tb
(bh char(8) default dbo.f_nextbh(),
col int)
--插入表的数据
begin tran --开始事务
insert into tb(col) values(1)
insert into tb(col) values(2)
insert into tb(col) values(3)
delete tb where col=3
insert into tb(col) values(4)
insert into tb(bh,col) values(dbo.f_nextbh(),14)
commit tran --提交事务
--查询表
select * from tb
drop table tb
drop function f_nextbh