在业务系统中,我们经常要使用格式化流水编号,且流水编号是自动排序的,很多朋友就想到用自增,但是业务中不一定满足,今天就遇到一个客户需要格式生成业务编号的,业务需求如下:
1.编号连续
2.每月从1开始,最大5位,不足5位左边0补充
3.格式化为:编码=年(2位)+月(2位)+流水号(5位);
针对上述,写了一个存储过程,并附带一个表存储,没什么技术含量,技术大神飘过。
效果图如下:
存储流水编号的表:
CREATE TABLE [dbo].[data_Number] (
[nid] int IDENTITY(1,1) NOT NULL,
[ny] varchar(4) COLLATE Chinese_PRC_CI_AS NULL,
[nm] varchar(2) COLLATE Chinese_PRC_CI_AS NULL,
[number] varchar(10) COLLATE Chinese_PRC_CI_AS NULL,
[sindex] int NULL,
CONSTRAINT [PK__data_Num__DF97D0F537FA4C37] PRIMARY KEY CLUSTERED ([nid])
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
)
ON [PRIMARY]
GO
ALTER TABLE [dbo].[data_Number] SET (LOCK_ESCALATION = TABLE)
GO
EXEC sp_addextendedproperty
'MS_Description', N'id',
'SCHEMA', N'dbo',
'TABLE', N'data_Number',
'COLUMN', N'nid'
GO
EXEC sp_addextendedproperty
'MS_Description', N'年份',
'SCHEMA', N'dbo',
'TABLE', N'data_Number',
'COLUMN', N'ny'
GO
EXEC sp_addextendedproperty
'MS_Description', N'月份',
'SCHEMA', N'dbo',
'TABLE', N'data_Number',
'COLUMN', N'nm'
GO
EXEC sp_addextendedproperty
'MS_Description', N'当前编号',
'SCHEMA', N'dbo',
'TABLE', N'data_Number',
'COLUMN', N'number'
存储过程代码:
CREATE PROCEDURE [dbo].[GetNumber]
@rst AS varchar(10) OUTPUT
as
BEGIN
DECLARE @y VARCHAR(20);
DECLARE @m VARCHAR(2);
--取得年份和月份
set @y=DATEPART(yyyy,GETDATE());
set @y= RIGHT(convert(varchar,@y),2)
--月份拼凑
set @m=DATEPART(mm,GETDATE());
DECLARE @lg int;
SELECT @lg=len(@m);
if @lg=1
BEGIN
set @m='0'+@m;
END
--获取当前数据库最大的ID
DECLARE @mx INT;
SELECT @mx=MAX(sindex) FROM data_number where ny=@y and nm=@m;
if @mx is NULL --判断是否为空
BEGIN
set @mx=1;
END
else
BEGIN
set @mx=@mx+1;
END
set @rst=REPLICATE('0',5-len(@mx))+CONVERT(VARCHAR,@mx);
set @rst=@y+@m+@rst;
INSERT into data_Number(ny,nm,number,sindex) values (@y,@m,@rst,@mx);
RETURN @rst;
END
|