生成最大单号 scope_identity

-- 假定要给T_0101001创建一个Sequence
-- 创建表SeqT_0101001
create table SeqT_0101001(
      -- ID列为自增列
      SeqID int identity(1,1) primary key,
      -- Sequence值
      SeqVal varchar(1)
)

-- 创建从SeqT_0101001表获取最新Sequence值的存储过程
create procedure P_GetNewSeqVal_SeqT_0101001
as
begin
      -- 声明新Sequence值变量
      declare @NewSeqValue int
      -- 设置插入、删除操作后的条数显示取消
      set NOCOUNT ON
      -- 插入新值到SeqT_0101001表
      insert into SeqT_0101001 (SeqVal) values ('a')   
      -- 设置新Sequence值为插入到SeqT_0101001表的标识列内的最后一个标识值  
      set @NewSeqValue = scope_identity()   
      -- 删除SeqT_0101001表(不显示被锁行)
      delete from SeqT_0101001 WITH (READPAST)
-- 返回新Sequence值
return @NewSeqValue
END

--使用Sequence
Declare @NewSeqVal int
Exec @NewSeqVal =  P_GetNewSeqVal_SeqT_0101001
Print @NewSeqVal
select Convert(char(8),Getdate(),112) + right('00000'+CAST(@NewSeqVal AS varchar(5)),5) as mySeq

--TRUNCATE  table  SeqT_0101001
原文地址:https://www.cnblogs.com/zoumin123/p/9276631.html