实体编号唯一的处理

如果完全用代码中的sql来处理,总是会存在问题。尤其是碰到批量单据生成。

通过测试 使用如下存储过程,关键是要在事务中处理。可以达到要求

USE  [ Autask ]
GO
/* ***** Object:  StoredProcedure [dbo].[GetMaxID]    Script Date: 12/05/2011 11:42:00 ***** */
SET ANSI_NULLS  ON
GO
SET QUOTED_IDENTIFIER  ON
GO

--  =============================================
--
 Author:        xtechnet
--
 Create date: 2011年11月5日
--
 Description:    更新_entityMaxID相应的记录
--
 =============================================
ALTER  PROCEDURE  [ dbo ]. [ GetMaxID ]
     --  Add the parameters for the stored procedure here
     @EntityTable  varchar( 100)
AS
BEGIN

     alter  table _entityMaxID
     set (lock_escalation  =  table)
    
     -- 使用事务,关键
     SET    TRANSACTION    ISOLATION    LEVEL    REPEATABLE    READ 
     begin    tran 

     declare  @NextID  varchar( 20);
     declare  @CurrentID  varchar( 20);
     declare  @MaxID  int;
     --  SET NOCOUNT ON added to prevent extra result sets from
     --  interfering with SELECT statements.
     SET NOCOUNT  ON;
     set  @CurrentID = isnull(( select   MAX(MaxID)  from _entityMaxID  WITH (TABLOCKX)  where EntityTable  =  @EntityTable), ' 00000000 ')
     set  @MaxID = convert( int, @CurrentID);
     if( @MaxID = 0)
         set  @NextID = ' 00000001 ';
     else
         set  @NextID = replace( @CurrentID, @MaxID, @MaxID + 1)
     set  @NextID = Substring( @NextID,{fn Length( @NextID)} - 7, 8)
    
     if( @MaxID = 0)
         insert  into _EntityMaxID  WITH (TABLOCKX)  (MaxID,EntityTable)  values( convert( int, @NextID), @EntityTable)
     else
         update _EntityMaxID  WITH (TABLOCKX)  set MaxID  =  convert( int, @NextIDwhere EntityTable  =  @EntityTable
     -- return @NextID
     --  Insert statements for procedure here
     -- waitfor   delay   '00:00:00' 
     -- 事务结束 
     commit  tran 
     SELECT  @NextID
END

 

你可能感兴趣的:(处理)