`
yeak2001
  • 浏览: 102782 次
  • 性别: Icon_minigender_1
  • 来自: 无锡
社区版块
存档分类
最新评论

Simulating Sequence Objects in SQL Server

阅读更多

Many applications need sequentially incremental number as unique/primary key of records.  SQL Server 2005 today supports identity column as the primary mean to general sequence number, which generates the sequence number upon the execution of DML (insert) or bulk insert.  The value of the insertion is known (when using insertion DML), post the execution of the DML.  In some implementations, the sequence numbers (or next unique incremental number) need to be generated prior to the DML operation.  For example, if sequence number can be retrieved prior to the DML operation, it can be easily implemented in situations where multiple DML (inserts, or even updates) using the same sequence number can be performed, and data can be insert into different tables, for example, parent-child, or based on the sequence value, data can be insert into different tables.

SQL Server 2005 Migration Assistant (SSMA) provides a different mechanism for sequence number generation.  SSMA’s approach is to use a single table to hold all the sequence numbers.  Each sequence number object is represented by a single row of record, which holds the property of the sequence, e.g. sequence name, current value, increments…etc.  The generation of the next value is invoked by an extended stored procedure in order to minimize the impact on application concurrency – the execution of extended procedure is not within the transaction scope of the DML statement, and it holds very short duration locks on the row that represents the sequence number.

This BLOG describes two more methods of sequence number generation.

Option 1
This option is easy to use and maintain, but it is suitable only with lower volume invocations.  It is also one of the widely used approaches, and often misused.  This method uses a single table to hold all the sequences needed for the application, and each sequence is represented by one single record, thus serializes operation requesting next value of the same sequence number.


1.      Create the following objects

Table AllSequences holds the information of all the sequences.  As a simple example, the table and subsequent stored procedure is kept quite simple.  Further enhancement is certainly possible based on the needs – for example, additional information of sequence such as maximum range, minimum range, loopback(yes/no) can be added.

·         SeqName – name of the sequence
·         Seed – seed value of the sequence
·         Incr – incremental value of the sequence
·         Currval – current value of the sequence


Create table AllSequences (
      SeqName nvarchar(255) primary key, -- name of the sequence
      Seed int not null default(1), -- seed value
      Incr int not null default(1), -- incremental
      Currval int
)
Go

The following stored procedure is used to create a sequence.  The following input parameter is expected:
·         SeqName – name of the sequence
·         Seed – seed value of the sequence
·         Incr – incremental value of the sequence


create procedure usp_CreateNewSeq
      @SeqName nvarchar(255),
      @seed int = 0,
      @incr int = 1
as
begin
      declare @currval int
      if exists (
            select 1 from AllSequences
            where SeqName = @SeqName )
      begin
            print 'Sequence already exists.'
            return 1  
      end

      if @seed is null set @seed = 1
      if @incr is null set @incr = 1
      set @currval = @seed

      insert into AllSequences (SeqName, Seed, Incr, CurrVal)
      values (@SeqName, @Seed, @Incr, @CurrVal)
    
end
go


The following stored procedure is used to generate the next value of the specified sequence through input parameter SeqName.

create procedure usp_GetNewSeqVal
      @SeqName nvarchar(255)
as
begin
      declare @NewSeqVal int
      set NOCOUNT ON
      update AllSequences
      set @NewSeqVal = CurrVal = CurrVal+Incr
      where SeqName = @SeqName
    
      if @@rowcount = 0 begin
print 'Sequence does not exist'
            return
      end

      return @NewSeqVal
end
go

   
2.      To create the new sequence, for example:
usp_CreateNewSeq N'TestSeq'

3.      To retrieving the new sequence value, for example for sequence “TestSeq”
usp_GetNewSeqVal N'TestSeq'

One thing to be careful is to keep the execution of the stored procedure usp_CreateNewSeq outside the scope of subsequent transaction which uses the sequence number generated.  This can minimize impact of blocking.

Typical usage
Declare @NewSeqVal int
Execute @NewSeqVal=usp_GetNewSeqVal @seqname=N'TestSeq'
print @NewSeqVal

Option 2
This method is intended for higher-throughput environments – such as thousands of transactions per second.  A table with identity column is created for every sequence.  Since the generation of identity value is lightweight, and not within the transaction scope of subsequent DML, this method can significantly improve the concurrency over the first method.  In addition, it also consumes less resource than extended procedure.


1.      Create one table with the following structure for each sequence, assuming seed 1, with increment of 1).
create table <tablename> (
      SeqID int identity(1,1) primary key,
      SeqVal varchar(1)
)

2.      Create the following stored procedure.  A delete operation is performed to remove the rows in the sequence table to reduce maintenance.  This obviously adds some load to the transaction however it should be quite minimal.  As an alternative, for higher throughput, the delete statement can be removed and a maintenance job can be scheduled during off-hour to purge the records in the table (truncate should not be used since it resets the identity value).
create procedure GetNewSeqVal_<tablename>
as
begin
      declare @NewSeqValue int
      set NOCOUNT ON
      insert into <tablename> (SeqVal) values ('a')
    
      set @NewSeqValue = scope_identity()
    
      delete from <tablename> WITH (READPAST)
return @NewSeqValue
end

3.      To retrieve the new value in a result set, simply execute the following:
GetNewSeqVal_<tablename>


Typical usage
            Declare @NewSeqVal int
            Exec @NewSeqVal =  GetNewSeqVal_<tablename>
          

Among the two options described above, Option 1 is widely used in different variations but prone to blocking/deadlocking.  Option 2 improves concurrency significantly with a simple approach.
分享到:
评论

相关推荐

    Simulating Changes in Soil Organic Carbon in Bangladesh with the

    A thesis submitted to McGill University in partial fulfillment of the requirements of the degree of Master’s of Science

    Simulating Ocean Water

    and artists an introduction to methods of simulating, animating, and rendering ocean water environments. CG water has become a common tool in visual effects work at all levels of computer graphics, ...

    Simulating planar reflection using two-pass rendering and texture mapping

    Simulating planar reflection using two-pass rendering and texture mapping 1. There ‘s a table with flat rectangular semi-reflective table-top in the 3D scene 2. On/Around the table are some 3D ...

    《Simulating Physics with Computers》

    ### 《Simulating Physics with Computers》—费曼的先见之明 #### 一、引言与背景 在1982年的国际理论物理杂志上,著名物理学家理查德·费曼发表了一篇名为《用计算机模拟物理学》的文章。这篇文章不仅对当时的...

    Simulating Spacecraft Systems2009.pdf

    Library of Congress Control Number: 2009932687 Springer-Verlag Berlin Heidelberg 2009 Springer Series in Aerospace Technology ISSN 1869-1730 e-ISSN 1869-1749

    S7-PLCSIM Simulating Modules

    《S7-PLCSIM:实现模块仿真与教学实践》 在工业自动化领域,西门子的S7-PLCSIM模拟软件是一款不可或缺的工具,它为用户提供了无需实际硬件即可进行PLC(可编程逻辑控制器)系统测试和验证的能力。...

    simulating wireless communication systems C++代码

    在无线通信系统模拟方面,C++是一种常用的编程语言,因为它提供了高效的执行能力和强大的库支持。以下是对给定的文件和标签的详细解释: 1. **无线通信系统模拟**:无线通信系统模拟涉及到对真实世界无线通信系统的...

    Simulating and optimising design decisions in quantitative goal models

    ### 模拟与优化定量目标模型中的设计决策 #### 摘要与介绍 本文讨论了在需求工程中模拟和优化定量目标模型的设计决策过程。文章由William Heaven和Emmanuel Letier撰写,他们来自伦敦大学学院计算机科学系。...

    abbr_ Synthesizing, and Simulating ASICs and FPGAs using VHDL or Verilog.part04

    abbr_ Synthesizing, and Simulating ASICs and FPGAs using VHDL or Verilog.part04

    Simulating Clouds with Procedural Texture

    Simulating Clouds with Procedural Texture

    simulating the SUI Channel Models.pdf

    标题:模拟SUI信道模型 描述:这份文档是针对固定无线应用的信道模型的补充资料,旨在帮助实现这些模型到软件信道模拟器中。文档深入解释了一些在原模型描述中未详述的问题,并提供了MATLAB代码作为更广泛模拟的...

    Python Cookbook, 2nd Edition

    Looping over Items and Their Indices in a Sequence Recipe 4.5. Creating Lists of Lists Without Sharing References Recipe 4.6. Flattening a Nested Sequence Recipe 4.7. Removing or Reordering ...

    python3.6.5参考手册 chm

    PEP 3333: Python Web Server Gateway Interface v1.0.1 Other Language Changes New, Improved, and Deprecated Modules email elementtree functools itertools collections threading datetime and time ...

    Simulating Husky 仿真代码

    标题 "Simulating Husky 仿真代码" 暗示了我们正在讨论如何在虚拟环境中模拟一个名为 Husky 的机器人。Husky 是一种由 Clearpath Robotics 设计的四轮驱动的机器人,常用于研究和教育目的。在机器人操作和算法开发中...

    simulating-ocean-wate.pdf

    本文件“simulating-ocean-water.pdf”显然聚焦于海洋水体的模拟技术,这是一个复杂且至关重要的议题,因为海洋是地球气候系统的关键组成部分。下面我们将深入探讨这一主题,了解其相关知识点。 一、海洋模型基础 ...

    Simulating Ocean Water-附件资源

    Simulating Ocean Water-附件资源

    matlabturbo.rar_BCJR MATLAB PDF_BCJR Equalization_Modified_bcj

    open source library for simulating turbo codes in matlab Turbo EqualizationInstead of that, a modified BCJR algorithm is used. .... open source library for simulating turbo codes in matlab Turbo ...

Global site tag (gtag.js) - Google Analytics