MS Sql Server 伪序列

先创建一个序列表

if exists (select 1

            from  sysindexes
           where  id    = object_id('TSysSequence')
            and   name  = 'In_SeName'
            and   indid > 0
            and   indid < 255)
   drop index TSysSequence.In_SeName
go

if exists (select 1
            from  sysobjects
           where  id = object_id('TSysSequence')
            and   type = 'U')
   drop table TSysSequence
go

/*==============================================================*/
/* Table: TSysSequence                                          */
/*==============================================================*/
create table TSysSequence (
   SeName               nvarchar(50)         not null,
   Increment            int                  not null default 1,
   CurVal               bigint               not null default 0
)
go

if exists (select 1 from  sys.extended_properties
           where major_id = object_id('TSysSequence') and minor_id = 0)
begin 
   declare @CurrentUser sysname 
select @CurrentUser = user_name() 
execute sp_dropextendedproperty 'MS_Description',  
   'user', @CurrentUser, 'table', 'TSysSequence' 
 
end 

select @CurrentUser = user_name() 
execute sp_addextendedproperty 'MS_Description',  
   '
   模拟oracle序列
   
   不允许用户维护,数据库初始化以后不允许任何人修改其中的值。
   
   默认生成名称为“DID”和“SID”的两个序列,意义为“数据序列号”和“系统序列号”。', 
   'user', @CurrentUser, 'table', 'TSysSequence'
go

insert into TSysSequence (SeName,Increment,CurVal) values ('DID',1,0) ;
insert into TSysSequence (SeName,Increment,CurVal) values ('SID',1,0) ;

/*==============================================================*/
/* Index: In_SeName                                             */
/*==============================================================*/
create unique index In_SeName on TSysSequence (
SeName ASC
)

go

再创建一个存储过程完成序列的使用

if exists (select 1
          from sysobjects
          where  id = object_id('PGetSequenceValue')
          and type in ('P','PC'))
   drop procedure PGetSequenceValue
go

create procedure PGetSequenceValue
  @SeName   nvarchar(50),
  @SeVal    bigint out
as
begin
  if not exists(select 1 from TSysSequence  where SeName = @SeName)
  begin
    raiserror('不存在序列%s',16,1,@SeName)
    return
  end

  update TSysSequence set @SeVal = CurVal + Increment, CurVal = CurVal + Increment where SeName = @SeName

end
go


使用方法

  declare @ID1 int  

  EXEC PGetSequenceValue 'SID',@ID1 OUTPUT

 select @ID1

  declare @ID2 int  

  EXEC PGetSequenceValue 'DID',@ID2 OUTPUT

  select @ID2


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weichao9999

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值