1. 创建一个表,用于存现在最大的ID
SELECT [ID],[PreFix],[Code] FROM [DocumentNO]
2. 增加SP,利用锁表,生成相应的ID
Create PROCEDURE [dbo].[GeneralDocumentNo]
(
@preFix nvarchar(256),
@outCode varchar(256) output
)
AS
BEGIN
-- =============================================
-- Author: xiefs
-- Create date: 2013-12-18
-- Description: 生成系统唯一序列号
-- =============================================
Declare @docNo nvarchar(256),
@month varchar(10),
@day varchar(10),
@no varchar(10),
@num int ,
@lenNum int,
@sql nvarchar(4000),
@maxCode varchar(256),
@tableName varchar(256) SET NOCOUNT ON;
set @tableName='DocumentNo';
set @month=CAST(month(getdate())as varchar);
set @day = CAST(day(getdate())as varchar);
if(LEN(@month)=1) set @month=''+@month;
if(LEN(@day)=1) set @day=''+@day; set @docNo = @preFix+cast(YEAR(getdate()) as varchar)+ @month+@day;
set @sql =N'select top 1 @p=code from '+@tableName +' WITH(holdlock,tablockx) where CHARINDEX('''+@docNo+''',code)=1 order by id desc';
EXEC sp_executesql @sql,N'@p varchar(256) output',@p=@maxCode output ;
if(@maxCode is null)
begin
set @no='';
end;
else
begin
set @no=CAST((CAST(SUBSTRING(@maxCode,len(@docNo)+1,LEN(@maxCode)) as int)+1) as varchar);
end; set @lennum = LEN(@no);
set @num =4;
while @lenNum<4
begin
set @lenNum=@lenNum+1;
set @no=''+@no;
end
insert into documentno(Prefix,Code) values(@preFix,@docNo+@no);
--select @docNo+@no;
set @outCode=@docNo+@no;
END