编号字段以字母和数字组成,并且数字可以自动增长

来源:互联网 发布:mac word转pdf缺失 编辑:程序博客网 时间:2024/05/21 22:54

下面的代码生成长度为8的编号,编号以BH开头,其余6位为流水号。并且保证流水号的连续性
--得到新编号的函数
CREATE FUNCTION f_NextBH()
RETURNS char(8)
AS
BEGIN
RETURN(SELECT 'BH'+RIGHT(1000001+ISNULL(RIGHT(MAX(BH),6),0),6) FROM tb WITH(XLOCK,PAGLOCK))
END
GO

--在表中应用函数
CREATE TABLE tb(
BH char(8) PRIMARY KEY DEFAULT dbo.f_NextBH(),
col int)

--插入资料
BEGIN TRAN
INSERT tb(col) VALUES(1)
INSERT tb(col) VALUES(2)
INSERT tb(col) VALUES(3)
DELETE tb WHERE col=3
INSERT tb(col) VALUES(4)
INSERT tb(BH,col) VALUES(dbo.f_NextBH(),14)
COMMIT TRAN

--显示结果
SELECT * FROM tb
/*--结果
BH col 
---------------- ----------- 
BH000001 1
BH000002 2
BH000003 4
BH000004 14
--*/

--另一种方法

--种子表 num_tb 
if object_id('num_tb') is not null
drop table num_tb
go
create table num_tb(d datetime,id int)
insert num_tb select getdate(),1 
if object_id('tb') is not null
drop table tb
go
create table tb(id varchar(20),name varchar(10)) 

create clustered index idx_clu_tb on tb(id) 
go 

create trigger tri_tb on tb INSTEAD OF INSERT 
as 
begin 
set nocount on 
declare @i int,@id varchar(20),@j int 
select @i=count(*) from inserted 
begin tran 
update num_tb with(TABLOCKX) set 
id=(case when convert(char(8),d,112)=convert(char(8),getdate(),112) 
then id+@i else @i end), 
@j=(case when convert(char(8),d,112)=convert(char(8),getdate(),112) then id else 0 end), 
d=getdate() 
commit tran 
select * into #t from inserted 
update #t set id=convert(varchar(8),getdate(),112)+right('00000'+rtrim(@j),5),@j=@j+1 
insert tb select * from #t 
end 
go 




--插入记录测试 

insert into tb(name) values('张三') 
insert into tb(name) values('李四') 
select * from tb
/*
id name
-------------------- ----------
2010012700002 张三
2010012700003 李四
*/
insert into tb select '2010012700003','王五'
/*
id name
-------------------- ----------
2010012700002 张三
2010012700003 李四
2010012700004 王五

*/

原创粉丝点击