步步为营-106-“流水号”自增长

这里所谓的流水号,仅仅是一个代称,是指数据库中字符串格式的自增长。例学生编码(系统自动生成P0001、P0002...,)

当然实现的方式也很多,如果不考虑并发和锁表问题的话,代码实现起来也容易。但是本次是通过最简单数据库函数来实现。
1:建表

CREATE TABLE [dbo].[studentinfo](
    [StudentGuid] [nchar](10) NOT NULL,
    [Name] [nchar](10) NULL
) ON [PRIMARY]
建表

2:创建函数

create function P_QIM_Print_Parm_mster()
returns varchar(7)
as
begin
declare @studentGuid varchar(7)
select @studentGuid='P'+RIGHT(1000000+ISNULL(RIGHT(MAX(studentGuid),6),0)+1,6)--查找表中该列中的最大值取到后(右)6位,最大的+1
from StudentInfo
return @studentGuid
END
创建函数

3:给表添加函数

ALTER TABLE studentinfo  ADD DEFAULT ([dbo].[P_QIM_Print_Parm_mster]()) FOR StudentGuid 
给表添加函数

4:测试用例

猜你喜欢

转载自www.cnblogs.com/YK2012/p/9472276.html